ただのメモです。
カメラロールを開く
写真を選択させる。
- (IBAction)attachmentFile:(id)sender {
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.delegate = self;
[controller setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:controller animated:YES completion:nil];
}
コールバック
写真選択された場合
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// カメラロールを閉じます。
[picker dismissViewControllerAnimated:YES completion:nil];
// Pathを取得
NSURL *referenceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
// AssetsLibratyを作成
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:referenceURL resultBlock:^(ALAsset *asset) {
// まずassetからバッファをつくる
ALAssetRepresentation *rep = [asset defaultRepresentation];
Byte *buffer = (Byte*)malloc(rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
NSData *imageData = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
// 取得したデータから拡張子を取得
NSString *fileExtension = [asset valueForProperty:ALAssetPropertyRepresentations][0];
fileExtension = [fileExtension pathExtension];
// ファイル名を生成する。
_attachmentFileCount++;
NSString *fileName = [NSString stringWithFormat:@"写真.%@", fileExtension];
// サムネイルを取得します。(このコードでは使いません。)
UIImage *image = [UIImage imageWithCGImage:[asset thumbnail]];;
// APIを呼び出します。(これは適当です。本当はAFHTTPClient内部の処理)
NSMutableURLRequest *request = [self multipartFormRequestWithMethod:@"POST" path:@"パス" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// ファイル名から拡張子を取得。(すでに拡張子は取れているが、、、メモなので・・)
NSString *mimeType = [NSString stringWithFormat:@"image/%@", [fileName pathExtension]];
// マルチパートデータに詰める。
[formData appendPartWithFileData:imageData name:@"attach_file" fileName:fileName mimeType:mimeType];
}];
// 送信処理
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
// 成功時
} failure:nil];
[AFHTTPClient enqueueHTTPRequestOperation:operation];
}];
} failureBlock:^(NSError *error) {
// 画像データが取得できない場合
}];
}
最後に
僕が近々使う可能性があるコードを適当にまとめてます。
AFHTTPClientは多分使わないけど、後で見るかもしれないので書いておく。