davidOhara davidOhara - 4 years ago 147
iOS Question

Uploading a file with NSURLSession

I am trying to upload a file with the following method:

- (void)uploadWithTarget:(NSString *)url andFileData:(NSData *)file andMD5Checksum:(NSString *)checksum
{


NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];

NSURL * urll = [NSURL URLWithString:url];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:urll];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest addValue:checksum forHTTPHeaderField:@"Md5Hash"];
[urlRequest addValue:@"Keep-Alive" forHTTPHeaderField:@"Connection"];
[urlRequest addValue:@"xml" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPBody:file];


NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:urlRequest];
[dataTask resume];


}


Delegate:

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
{
NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Received String %@",str);
}


But i always get the error from my server that there isn´t a file attached! What´s wrong?

Answer Source

The content type of your HTTP request needs to be multipart/form-data. Also the body must be formed as a multipart request. You can find a tutorial here: http://web.archive.org/web/20140311092840/http://zcentric.com/2008/08/29/post-a-uiimage-to-the-web/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download