NSMutableURLRequest
に含まれるカスタム投稿データを使用して を作成するために使用する次の方法がありますNSMutableDictionary
。
+ (NSMutableURLRequest *)createURLRequestWithURL:(NSString *)URL andPostData:(NSMutableDictionary *)postDictionary {
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]init];
NSString *postString = @"";
NSString *postLength = nil;
NSData *postData = nil;
//convert post distionary into a string
if (postDictionary) {
for (NSString *key in postDictionary) {
if ([postString length] != 0) {
postString = [postString stringByAppendingString:@"&"];
}
postString = [postString stringByAppendingFormat:@"%@=%@", [self urlEncodeString:key], [self urlEncodeString:[postDictionary valueForKey:key]]];
}
}
//get length of post and convert post into a data object
postLength = [NSString stringWithFormat:@"%d", [postString length]];
postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//setup the request
[urlRequest setURL:[NSURL URLWithString:URL]];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPBody:postData];
return urlRequest;
}
この時点まで、私は の値として文字列データのみを使用してきましたpostDictionary
。
私の質問は、このコードを変更して他の種類の値を送信するにはどうすればよいですか? 具体的には、画像をサーバーに送信しようとしています。