I have the following method that I use to create a NSMutableURLRequest with custom post data contained within a 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;
}
Up until this point I’ve been using only string data as the values in the postDictionary.
My question is how should I modify this code to send other kinds values? Specifically I’m trying to send images to the server.
Used the info from the other answers to modify my code as needed: