2

I'm using NSUrlSessionTaskDelegate to upload files into a server, but server codes aren't given back in the didCompleteWithError. This matches the apple documentation:

Server errors are not reported through the error parameter. The only errors your delegate receives through the error parameter are client-side errors, such as being unable to resolve the hostname or connect to the host.

But is there any other way I can get the server error's like a 400 Bad Request or something? Because every file upload is a success now even when I get a bad request back..

O-mkar
  • 5,430
  • 8
  • 37
  • 61
Mittchel
  • 1,896
  • 3
  • 19
  • 37

2 Answers2

3

Something like this should work. But I didn't test it. It is posted as an answer just because of easier code formatting...

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
    if (!error)
    {
        NSHTTPURLResponse *response = task.response;

        NSLog(@"StatusCode: %d",response.statusCode);

        if (response.statusCode != 200) //note that other 2xx codes might be valid
        {
            //....
        }
    }
    else
    {
        NSLog(@"Error: %@",error.description);
    }
}
Rok Jarc
  • 18,765
  • 9
  • 69
  • 124
  • @Joseph Lord: I just tried to upvote yout answer but you deleted it. It was correct. – Rok Jarc Dec 04 '15 at 11:36
  • Amazing thank you @rokjarc. Just one question remains.. I'm also getting a message back when something goes wrong. Anyway to retrieve that? – Mittchel Dec 05 '15 at 08:50
  • You could, but the actual implementaton depends a bit on how you initiate the upload process. One way would be using `NSURLSessionDataDelegate` protocol. Please check if [this post](http://stackoverflow.com/a/23738200/653513) helps you. Or you might pass this message from server in some kind of custom HTTP header and catch it directly in `- (void)URLSession:task:didCompleteWithError:` (the `allHeaderFields` property of a response - i'd use a `Warning `key in this case). HTTP header solution is possible only if you have control over the server of course. – Rok Jarc Dec 05 '15 at 09:39
0

In SWIFT 5, you can do the same like below.

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
            
     print(task.response ?? "")
            
     if let urlResponse = task.response as? HTTPURLResponse {
         print(urlResponse.statusCode)
     }
}
Alex Andrews
  • 1,498
  • 2
  • 19
  • 33