Search code examples
iosswiftpostrequestalamofire

Why I get this error while trying to make post request to a server in iOS Swift: unexpectedly found nil while unwrapping an Optional value?


 func uploadImage(var image:UIImage)
{
    var imageData = UIImagePNGRepresentation(image)
    let base64String = imageData!.base64EncodedStringWithOptions([.Encoding64CharacterLineLength]) 
    let parameters = [
        "img": base64String
    ]

    Alamofire.request(.POST, API_URL, parameters:parameters) .response {
        (request, response, data, error) in   
    }    
}

The image is not nil. And I cannot find which value is actually nil.


Solution

  • imageData is probably nil. Always do nil checks and avoid unwrapping.

    func uploadImage(var image:UIImage) {
      if let imageData = UIImagePNGRepresentation(image), let base64String = imageData.base64EncodedStringWithOptions([.Encoding64CharacterLineLength]) {
        let parameters = [
          "img": base64String
        ]
    
        Alamofire.request(.POST, API_URL, parameters: parameters) .response {
          (request, response, data, error) in   
        }
      }    
    }