Monthly Archives: January 2010

iPhoneによる位置情報関係のまとめ

以下はiPhoneによる位置情報関係のまとめ | アクトインディ技術部隊報告書と同様のものです。

今回も前回のGeohashに引き続き、位置情報に関する内容です。
ググれば出てくる内容なので、新しいことはなんにもないのが申し訳ないところです。

位置情報に関するライブラリは

  • CoreLocation
  • MapKit

などがあります。

GPSで現在位置を取得するにはCoreLocationを使用し、地図を表示したり現在地の大まかな住所を取得するためにはMapKitを使用します。

GPSで現在位置を取得するには

CoreLocationではCLLocationManagerDelegateを実装し

- (void)setup
{
    CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    if ([locationManager locationServicesEnabled])
    {
        [locationManager setDelegate:self];
        [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        [locationManager setDistanceFilter:kCLDistanceFilterNone];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"%@", newLocation);
}

このようにすればLogに現在地の情報が取得できます。

地図を表示するには

- (void)setup
{
    CGRect screen = [[UIScreen mainScreen] bounds];
    MKMapView *mapView = [[MKMapView alloc] initWithFrame:screen];
    [[self view] addSubview:mapView];
    [mapView release];

    MKCoordinateRegion  region;
    region.center = [location coordinate];
    region.span.latitudeDelta = 0.005;
    region.span.longitudeDelta = 0.005;
    [mapView setRegion:region animated:YES];
}

とすれば、locationで指定した座標に移動します。

現在地を取得するには

MKReverseGeocoderDelegateを実装し

- (void)setup
{
    MKReverseGeocoder *reverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:[location coordinate]];
    [reverseGeocoder setDelegate:self];
    [reverseGeocoder start];
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
    NSLog(@"%@", [placemark title]);
}

とすることで取得することができます。
すべてのAPIが非常にシンプルに作られているので、使用するのは非常に簡単です。

コメントをDISQUSを使用したものに変更しました。

このblogのコメントをDisqusを使用したものに変更しました。
既存のものはimportしました。

手順としては

  1. WordPressのPluginであるDISQUS Comment Systemをダウンロードし、wp-contents/pluginsにインストール。
  2. WordPressの管理画面の”Settings” – “DISQUS”にゆく。
  3. “Import comments into Disqus”ボタンを押して既存のコメントをDisqusにインポートする(しばらくかかるのでしばし待つ)。

多分これぐらいで、超簡単に導入することができました。
てっきりコメントのインポートがかったるいものだと考えていたのですが、そんなことはなく、もっと早くやっておけばよかったと思いました。

Objective-C的???Geohash

以下はObjective-C的???Geohash | アクトインディ技術部隊報告書と同様のものです。

先日chibaさんがGeohashをdecodeするものをCLで書いていらしたので、それを微妙に参考にしながらCocoaのCoreLocationのCLLocationにgeohashをencode/decodeするメソッド追加してみました。

本当はビット演算がしたいのですが、文字列処理の方が自分には単純で簡単だったため、とりあえず今回は文字列処理にしてみました。

我ながらひどいコードだと思いますので、これからリファクタリングをしていきたいところです。

[CLLocation+Geohash.h]

#import <CoreLocation/CoreLocation.h>
#import <Foundation/Foundation.h>


@interface CLLocation(Geohash)

@property (nonatomic, readonly)   NSString    *geohash;

+ (CLLocation *)locationFromGeohash:(NSString *)aGeohash;

@end

[CLLocation+Geohash.m]

#import "CLLocation+Geohash.h"

#include <math.h>

NSString *int_to_binary(NSUInteger input)
{
    if (input == 1 || input == 0)
    {
        return [NSString stringWithFormat:@"%d", input];
    }

    return [NSString stringWithFormat:@"%@%d", int_to_binary(input / 2), input % 2];
}


double parse_binary(NSString *binary, double max, double min)
{
    double mid = 0.0;
    
    for (NSUInteger i = 0; i < [binary length]; ++i)
    {
        if ([binary characterAtIndex:i] == '1')
        {
            min = mid;
        }
        else
        {
            max = mid;
        }
        
        mid = (max + min) / 2;
    }
    
    return mid;
}


NSUInteger binary_to_int(NSString *input)
{
    NSUInteger result, length;

    result = 0;
    length = [input length];

    for (NSUInteger i = 0; i < length; ++i)
    {
        if ([input characterAtIndex:i] == '1')
        {
            result += pow(2, length - i - 1);
        }
    }

    return result;
}


NSString * generate_binary(double input, double max, double min, int cutoff)
{
    NSMutableString     *result;
    double              mid;

    result = [NSMutableString string];
    for (int i = 0; i < cutoff; ++i)
    {
        mid = (max + min) / 2;

        if (input > mid)
        {
            [result appendString:@"1"];
            min = mid;
        }
        else
        {
            [result appendString:@"0"];
            max = mid;
        }
    }

    return [NSString stringWithString:result];
}


@implementation CLLocation(Geohash)

- (NSString *)geohash
{
    int cutoff = 15;
    NSString *base32_characters  = @"0123456789bcdefghjkmnpqrstuvwxyz";

    NSString            *bin_lat, *bin_lng;
    NSMutableString     *bin_packed, *result;
    
    bin_lat = generate_binary([self coordinate].latitude, 90.0, -90.0, cutoff);
    bin_lng = generate_binary([self coordinate].longitude, 180.0, -180.0, cutoff);

    bin_packed = [NSMutableString string];

    for (int i = 0; i < [bin_lat length]; ++i)
    {
        [bin_packed appendFormat:@"%c%c", [bin_lng characterAtIndex:i], [bin_lat characterAtIndex:i]];
    }

    result = [NSMutableString string];

    // extract by 5-bit.
    for (int i = 0; i < [bin_packed length] / 5; ++i)
    {
        NSUInteger index;
        index = binary_to_int([bin_packed substringWithRange:NSMakeRange(i * 5, 5)]);
        [result appendFormat:@"%c", [base32_characters characterAtIndex:index]];
    }

    return result;
}


+ (CLLocation *)locationFromGeohash:(NSString *)aGeohash
{
    NSString *base32_characters  = @"0123456789bcdefghjkmnpqrstuvwxyz";

    NSMutableString *bin_packed, *bin_lat, *bin_lng;

    bin_packed = [NSMutableString string];

    for (NSUInteger i = 0; i < [aGeohash length]; ++i)
    {
        NSString *character;
        character = [[NSMutableString stringWithFormat:@"%c", [aGeohash characterAtIndex:i]] lowercaseString];

        for (NSUInteger j = 0; j < [base32_characters length]; ++j)
        {
            if ([character isEqualToString:[NSString stringWithFormat:@"%c", [base32_characters characterAtIndex:j]]])
            {
                NSMutableString *binary;
                binary = [NSMutableString stringWithFormat:@"%@", int_to_binary(j)];

                NSUInteger length = [binary length];
                for (NSUInteger k = 0; k < 5 - length; ++k)
                {
                    [binary insertString:@"0" atIndex:0];
                }

                [bin_packed appendString:binary];
                break;
            }
        }
    }

    bin_lat = [NSMutableString string];
    bin_lng = [NSMutableString string];

    for (NSUInteger i = 0; i < [bin_packed length]; ++i)
    {
        if (i % 2)
        {
            // a latitude is composed of odd bits. 
            [bin_lat appendFormat:@"%c", [bin_packed characterAtIndex:i]];
        }
        else
        {
            // a longitude is composed of even bits.
            [bin_lng appendFormat:@"%c", [bin_packed characterAtIndex:i]];
        }
    }

    return [[CLLocation alloc] initWithLatitude:parse_binary(bin_lat, 90.0, -90.0)
                                      longitude:parse_binary(bin_lng, 180.0, -180.0)];
}


@end

NSStringでかなり遅いcharacterAtIndexを使いまくっている。

参考

Geohash – Wikipedia, the free encyclopedia
GeoHashのdecodeのアルゴリズムの解説します & ScalaのGeoHashライブラリを作ってみました(仮) – ゆろよろ日記

Delaunay Tessellation for iPhone

以下の文章はDelaunay Tessellation for iPhone | アクトインディ技術部隊報告書と同様のものです。

プログラムプレゼンテーションの第2回は、iPhoneを用いてDelaunay分割をするというものにしてみました。

本当は他のものをやるつもりだったのですが、前回のプログラムプレゼンテーションではkomagataさんがObjective-Cのキメラさ、カオスさをおもしろがっていたと勝手に仮定して、Objective-C++でさらなるカオスさを目指すことにしました。

そんな折りに以前ドロネー分割をするためのプログラムをつくって、アップロードしようかなといっていたのを思い出しました。

ということで、今回はそれを流用することにしました。
単純に移植するだけだから簡単だろと思ったところ、意外と手直しに時間がかかってしまいました。

ドロネー分割については計算幾何学で出てくるものですが、この余白はそれを書くのにはせますぎるということで、ググればきっとわかる!!!

ソースコードはこちらです。
ライブラリとしてBoost C++ Librariesを使用しています。

実行すると、毎回ランダムな10点を作成し、下図のようにドロネー分割された図が表示されます。

Delaunay tessellation   Delaunay tessellation with circumcircles

右側の図は外接円も表示させた場合です。
ドロネー分割では生成された三角形によって作られる外接円の中に、その三角形以外の点が含まれてはいけません。

ランダムな点を生成する部分にはboost::randomを用い、ドロネー分割を計算する部分はC++で書かれています。

Objective-CとC++のコードを混ぜる場合の注意点は、HMDTさんによくまとめられているのでこちらを参照していただくのがよいかと思います。
HMDT – Objective-C++

Objective-C++のソースを書かれるときは、.mとなっている拡張子を.mmにしてくださいね。
自分はこれをしないでObjective-C++のファイルだと認識されずはまりまくりました。

こんな風にC++のコードも簡単に使用することができるので、Objective-Cを使われている皆様もぜひ組み合わせてみてはいかがでしょうか???

P.S.
本当はNSOperationを使って、スレッドを新しく作ってバックグラウンドで処理をしたかったのですが、プログラムの構造上面倒なのでやめました。

参考
Objective-C プログラミング言語:C++ と Objective-C の併用
HMDT – Objective-C++

複数行にわたったテキストを含むUILabelを適切な高さに調節する。

複数行にわたったテキストを表示するためのUILabelのインスタンスであるlabelがあり、そのlabelを適切なサイズ高さに変更したい時がありました。

// すでに以下の2行は他の部分で設定されている。
[label setLineBreakMode:UILineBreakModeWordWrap];
[label setNumberOfLines:0];

CGRect *frame;

frame = [label frame];
frame.size = CGSizeMake(WIDTH, 0);

[label setFrame:frame];
[label setText:@"long long long text..."];
[label sizeToFit];

ポイントはnumberOfLinesを0にすることと、sizeToFitメッセージを呼び出すこと。
numberOfLinesを0にしないと、sizeToFitを呼び出した時点で、指定した幅が無視されてしまう気がする。

毎回frameの幅を決めているのは、テキストが何度も書き換わる場所だから。
テキストが短いものになった場合、sizeToFitメッセージで短い幅が設定されてしまうと以降ずっとその短い幅になったままになってしまうため。

でもAppleのドキュメントには、以下のようにsizeToFitメッセージはnumberOfLinesを考慮するって書いてある。
自分のやり方がおかしいのか?

UILabel Class Reference」より抜粋

When the receiver is resized using the sizeToFit method, resizing takes into account the value stored in this property. For example, if this property is set to 3, the sizeToFit method resizes the receiver so that it is big enough to display three lines of text.

引用元: UILabel Class Reference

RSpecでMacro?を書く。

RSpecを使ってSpecを書いていると何度も同じことを書くことが多いです。

たとえばパラメータに応じてページタイトルを変えたい場合とか、validationがきちんと行われているかとか。。。
毎回、 it “should have hoge” do … end と書いているのは大変です。
RSpecではいくつかの方法を使用して、もっと簡単に書くことができます。

クラスメソッドを使う

一つのspecファイルで何度も使うものであればクラスメソッドにします。

[$RAILS_ROOT/spec/views/articles/index.html.erb_spec.rb]

describe "/articles" do
  def self.it_should_have_tag(selector, content)
    it "should have '#{content}' at '#{selector}'" do
      response.should(have_tag(selector, content))
    end
  end
end

と書いておけば、以下のような書き方が可能になります。

[$RAILS_ROOT/spec/views/articles/index.html.erb_spec.rb]

describe "/articles" do
  def self.it_should_have_tag(selector, content)
    it "should have '#{content}' at '#{selector}'" do
      response.should(have_tag(selector, content))
    end
  end

  it_should_have_tag('tr>td', 'MyString')
end

it_should_have_tag(‘tr>td’, ‘MyString’) の部分だけで適切なspecに展開されます。
1行で簡潔に書けますので、理解する時間も短くてすみます。

自分はページタイトル、meta description、meta keywords、RSSのスペックに以下のコードを使用しています。

[$RAILS_ROOT/spec/views/articles/index.html.erb_spec.rb]

describe "/articles" do
  def self.it_should_have_tag(selector, content)
    it "should have '#{content}' at '#{selector}'" do
      response.should(have_tag(selector, content))
    end
  end

  def self.it_should_have_page_title(title)
    it_should_have_tag('head>title', title)
  end

  def self.it_should_have_meta_description(meta_description)
    it_should_have_tag('head>meta[name=description][content=?]', meta_description)
  end

  def self.it_should_have_meta_keywords(meta_keywords)
    it_should_have_tag('head>meta[name=keywords][content=?]', meta_keywords)
  end

  def self.it_should_have_rss_link(link)
    it_should_have_tag('head>link[rel=alternate][type=application/rss+xml][href=?]', link)
  end
end

モジュールに追い出す

さらによく使う項目、上記のhtmlに関するspecなどはたくさんのところに書かれるであろうことが推測されます。
そういう場合には、モジュールに追い出してしまうということが可能だということを同僚のquekさんに教えていただきました。1

$RAILS_ROOT/spec/support フォルダにモジュールのファイルを書きます。
上記の例であれば

[$RAILS_ROOT/spec/support/tag_macros.rb]

module TagMacros
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def it_should_have_tag(selector, content)
      it "should have '#{content}' at '#{selector}'" do
        response.should(have_tag(selector, content))
      end
    end

    def it_should_have_page_title(title)
      it_should_have_tag('head>title', title)
    end

    def it_should_have_meta_description(meta_description)
      it_should_have_tag('head>meta[name=description][content=?]', meta_description)
    end

    def it_should_have_meta_keywords(meta_keywords)
      it_should_have_tag('head>meta[name=keywords][content=?]', meta_keywords)
    end

    def it_should_have_rss_link(link)
      it_should_have_tag('head>link[rel=alternate][type=application/rss+xml][href=?]', link)
    end
  end
end

使用する際には include TagMacros を書いておきます。

[$RAILS_ROOT/spec/views/articles/index.html.erb_spec.rb]

describe "/articles" do
  include TagMacros

  it_should_have_tag('tr>td', 'MyString')
end

自分のような include 〜 を書くのもものぐさだという人は、 $RAILS_ROOT/spec/spec_helper.rb に config.include メソッドを使用すれば、自動的に読み込まれるようになります。

[$RAILS_ROOT/spec/spec_helper.rb]

Spec::Runner.configure do |config|
  # ...
  config.include(TagMacros, :type => [:views])
  # ...
end

上記のように :type を指定すれば view だけで読み込まれるというような指定も可能です。

参考

Railscasts – RSpec Matchers & Macros
Writing Macros in RSpec • Blog Archive • Ben Mabey

P.S.
参考にしたサイトではMacroと書いてありますが、どうもこれをMacroと読んでいいものなのかどうかかなり謎なので、タイトルはMacro?と?付きにしてみましたwww

  1. quekさんによると、下の「参考」のところに書いた Railscasts に同様のことが書いてあり、そのアドレスを過去の自分は社内のチケットに書いていたらしいのですが、モジュールに出すことは全く知りませんでしたwww []