Search code examples
iosswiftnsurlconnection

unexpectedly found nil - error on File Upload with NSURLConnection


I am using the following function to upload a image to a given url. I built this function based on the answers given to these to questions: NSURLConnection Using iOS Swift and How to send UIImage in JSON format, by filling a NSDictionary

func uploadFileToUrl(url:NSURL){
    var request = NSMutableURLRequest(URL:url)
    request.HTTPMethod = "POST"
    request.HTTPBody = NSData.dataWithData(UIImagePNGRepresentation(image))

    var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
    var error: AutoreleasingUnsafeMutablePointer<NSErrorPointer?> = nil

    var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:nil)!


    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

    if (error != nil) {
        println("Request didn't go through")
    }

    println("Synchronous\(jsonResult)")
}

However when I run my app I always get an "fatal error: unexpectedly found nil while unwrapping an Optional value" on the following line:

    var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:nil)!

What am I doing wrong? Thanks


Solution

  • First off, you aren't passing your error pointer when you make the request, so you will never know if that failed.

    Secondly, as already mentioned, you are force unwrapping your dataVal variable without checking the value. So if your request did error and you don't handle it, you end up with the error you showed.

    See the code below for a working example.

    func uploadFileToUrl(url:NSURL){
        var request = NSMutableURLRequest(URL:url)
        request.HTTPMethod = "POST"
        request.HTTPBody = NSData.dataWithData(UIImagePNGRepresentation(image))
    
        var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
        var HTTPError: NSError? = nil
        var JSONError: NSError? = nil
    
        var dataVal: NSData? =  NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error: &HTTPError)
    
        if ((dataVal != nil) && (HTTPError == nil)) {
            var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: &JSONError) as NSDictionary
    
            if (JSONError != nil) {
                println("Bad JSON")
            } else {
                println("Synchronous\(jsonResult)")
            }
        } else if (HTTPError != nil) {
            println("Request failed")
        } else {
            println("No Data returned")
        }
    }