前回、カメラ画像を保持する処理まで作成していました。
この機能からの差分のコードは以下になります。
static NSString *CloudARAPIKey = @"Input your API Key!";
@interface CATMainViewController ()
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *captureVideoPreviewLayer;
@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (strong) UIImage *capturedImage;
- (void) initCaptureSession;
- (void) startCaptureSession;
- (void) stopCaptureSession;
- (void) cameraPreviewTouched:(UIGestureRecognizer *) sender;
@end
@implementation CATMainViewController
- (void) viewDidLoad {
[super viewDidLoad];
//キャプチャ初期設定
[self initCaptureSession];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget: self
action: @selector(cameraPreviewTouched:)];
[self.view addGestureRecognizer: tapGesture];
}
- (void) cameraPreviewTouched:(UIGestureRecognizer *) sender {
if (self.capturedImage != nil) {
// リクエストパラメータ作成
NSData *capturedImagePNGData = UIImagePNGRepresentation(self.capturedImage);
NSCharacterSet *abCharacterSet = [NSCharacterSet alphanumericCharacterSet];
NSString *base64ImageData = [[capturedImagePNGData base64EncodedStringWithOptions: 0] stringByAddingPercentEncodingWithAllowedCharacters: abCharacterSet];
NSString *requestBodyString = [NSString stringWithFormat: @"apiKey=%@&binData=%@",
CloudARAPIKey, base64ImageData];
NSData *requestBodyData = [requestBodyString dataUsingEncoding: NSUTF8StringEncoding];
// URLリクエスト作成
NSURL *apiURL = [NSURL URLWithString: @"http://api.ns-cloudar.com/api/marker/v1/imageSearch.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: apiURL];
[request setHTTPMethod: @"POST"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)requestBodyData.length]
forHTTPHeaderField: @"Content-Length"];
[request setHTTPBody: requestBodyData];
// 通信開始
[NSURLConnection sendAsynchronousRequest: request
queue:[NSOperationQueue mainQueue]
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
// サーバ応答対応
}];
}
}
@end
今回の実装内容は画面がタップされたら、そのときのcapturedImageをCloudARAPIβに投げ、反応を受けるまでとなります。
CloudAR APIキーの設定
まずは、第1回で取得したAPIキーを埋め込みます。
上のソースでは、CloudARAPIKeyという静的変数に予め登録するようにしています。
なお、APIキーについては、
API管理画面の「API キー」という項目を参照してください。
APIリクエストパラメータの確認
キーを入力したら、いよいよ通信処理の実装に移りましょう。
まず、
APIマニュアルを開いてみます。
そうすると、APIのURLとリクエストパラメータ一覧が記載されています。
必要な物はAPIキーと画像データのバイナリをBASE64エンコードした文字列のみ、非常にシンプルです。
cameraPreviewTouched:メソッドの冒頭でパラメータを作成しています。
ここで多少ネックとなりそうなのが、画像をBASE64エンコードする部分だと思うのですが、まず画像オブジェクトをJPEGまたはPNGファイルに変換します。
これは、以下の標準APIが利用できます。
NSData *UIImagePNGRepresentation(UIImage *image)
NSData *UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality)
次にBASE64エンコードについてですが、iOS7以降はNSDataクラスにこれを行う目的のメソッドが追加されました。
- (NSString *) base64EncodedStringWithOptions:(NSDataBase64EncodingOptions) options
今回はこちらを使用することにします。
もう1つ注意点があり、BASE64エンコード文字列をリクエストパラメータに含める場合、+などの文字列が含まれるのでこれをさらにURLエンコードします。
ただし、NSStringクラスのstringByAddingPercentEscapesUsingEncoding:では、+などの記号がエンコードされずに残ってしまうので、アルファベットと数字以外を全てエンコードさせるためにiOS7から追加された以下のメソッドを使用します。
- (NSString *) stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *) allowedCharacters
APIリクエストの作成
上で作成したパラメータを使用してリクエストを作成します。
メソッドはPOSTに設定し、とりあえずヘッダ情報としてContent-Lengthを付けています。
最後にボディデータとして、パラメータを埋め込みます。
APIリクエストの送信
リクエストの送信は、以下の非同期型の簡易メソッドを使用します。
+ (void) sendAsynchronousRequest:(NSURLRequest *) request
queue:(NSOperationQueue *) queue
completionHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError)) handler
これで現在映っているカメラの映像をCloudAR APIβへ問い合わせるところまで実装できました。
次回はレスポンスデータの受け取りについて取り上げたいと思います。
- 関連記事
-
スポンサーサイト