これは、ファイル(任意のファイル、画像、ビデオ、オーディオなど)をWebサービスにPOSTする方法です。
NSString *fileName = @"myAudio";
NSData *audioFile = [NSData dataWithContentsOfFile:@"myAudio.ext"]; //some audio
NSString *urlString = @"http://www.something.com/someservice";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSString *strPostLength = [NSString stringWithFormat:@"%d", [audioFile length]];
NSMutableURLRequest *uRequest = [[NSMutableURLRequest alloc] init];
[uRequest setURL:url];
[uRequest setHTTPMethod:@"POST"];
if (audioFile)
{
NSMutableData *body = [NSMutableData data];
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[uRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
/*
now lets create the body of the post
*/
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[uRequest setValue:strPostLength forHTTPHeaderField:@"Content-Length"];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.ext\"\r\n",fileName] dataUsingEncoding:NSUTF8StringEncoding]];
//userfile->サーバーコードで指定された変数名...
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:audioFile]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[uRequest setHTTPBody:body];
}
NSURLConnection *uConn=[[NSURLConnection alloc] initWithRequest:uRequest delegate:self];
if (uConn)
{
NSLog(@"Failed to connect to url");
}
uRequest = nil;
これがあなたの問題を解決するのに役立つことを願っています...