Hi everyone!
I'm using a backgroundSessionConfiguration and was reading the file to a NSData, creating the request manually and sending the data using:
self.uploadDataTask = [self.sessionURLBackground uploadTaskWithStreamedRequest:request];
I remember that it was the only way I made it to work. But it leads to memory leak and loss connection the the background service... Now I'm trying to use:
self.uploadDataTask = [self.sessionURLBackground uploadTaskWithRequest:request fromFile:[[NSURL alloc] initFileURLWithPath:self.pathFile]];
This should be the correct way and maybe get rid of the memory leaking problem... BUT... now I cant get my uploads to work... even if I set:
[request addValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
When I debug the request it ignores my Content-Type and it send this POST request to the PHP server:
{
args = {
};
data = "data:application/octet-stream;base64,/9j/4AAQSkZJRgABAQAASABIAA ...";
files = {
};
form = {
};
headers = {
Accept = "*/";
"Accept-Encoding" = "gzip, deflate";
"Accept-Language" = "pt-br";
Appagent = iOS;
"Content-Length" = 510900;
"Content-Type" = "image/jpeg";
Host = "httpbin.org";
Idsession = "xxxxxxxxxxxx-xxxx-xxxxx-xxxxxxx";
"User-Agent" = "SFTest/1 CFNetwork/758.1.6 Darwin/15.0.0";
};
json = "<null>";
origin = "xxx.xxx.xxx.xxx";
url = "http:/
}
It ignores my request Content-Type and sends in the "data" field as application/octet-stream instead of "files" field... and the PHP says that $_FILES is empty...
I tried image/jpeg and multipart/form-data, the image/jpeg is the one I posted and the multipart/form-data returns a server 500 Error from httpbin.org/post
You’re speaking PHP but NSURLSession speaks HTTP. In HTTP there is:
a request method
a set of headers
a request body
The “Content-Type” is an HTTP header. It is meant to describe the format of the data in the request body but NSURLSession does not enforce that. Nor does it provide any infrastructure for setting the request body to any of the various specialised formats out there.
I suspect that your PHP code is expecting the data to be formatted as “multipart/form-data” (see RFC 2388). If that’s the case then you’ll either have to change your client code to put the data in that format or change your server code to not require that format.
A lot of the time I use PUT rather than POST because servers generally make fewer implicit assumptions about the content of a PUT request.
IMPORTANT “multipart/form-data” is a common format for a POST request body but it’s not the only format in common use. Moreover, there’s no HTTP-level requirement as to the format of a POST request body, which is why NSURLSession isn’t able to do this work for you.
Share and Enjoy
—
Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"