[iphone][memo]HTTP通信して画像を投げる。
( diary )最近いろんな言語であっちこっち開発しているから頭パンクしてきそうな季節ですね。
意味分からないですね。nakajijapanです。
簡単にできるといいのにね。まぁでもある意味生のデータを生成しているのでわかりやすいっちゃわかりやすい。 抽象化したやつは後で自分でつくっておこっと。
//NSString *query = @"test=hoge&test2=hogehoge";
NSURL *url = [[NSURL alloc] initWithString:@"http://test.hoge/hoge/post.php"];
// GETでは使えない
CGFloat quality = 100.0;
NSData *postImage = [[[NSData alloc] initWithData:UIImageJPEGRepresentation(_imageView.image, quality)] autorelease];
// POST用
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithString:@"nakajijapan2011"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
// name=image dataの設定
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"image\";filename=\"source.jpg\"\r\n"]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg;\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:postImage];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// error
NSString *errorStr = [error localizedDescription];
if (0 < [errorStr length]) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"RequestError"
message:errorStr
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
今回の処理でいうと同期処理なので実際にiPhoneでユーザがスムーズにストレスなく操作することを考慮にいれると 非同期の処理かましたほうがいいんだけど、それはまた後ほど。
■参照URL https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html https://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/NSURLConnectionDelegate
