Search code examples
iosswiftalamofire

How to upload parameters with non-string value in upload method in Alamofire


My parameter is a [String:AnyObjecy] dictionary and i am using Alamofire upload method to upload an image. When i want to pass the parameters with it, using the method suggested by EdFunke (https://stackoverflow.com/a/33012955/4919289) i encounter the following errors: 'NSInvalidArgumentException', reason: '-[__NSCFNumber dataUsingEncoding:

during:

for (key, value) in params{
      print("before key: \(key)")
      multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
      print("after key:\(key)")
}

I guess it is because the value in the dictionaries are not string, how can i solve it?

updated at 27/2/2017 with Swift 3

    let params = [
        //your params
    ] as [String : Any]
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(self.user.imageData, withName: "your file name", fileName: "your file name with extension", mimeType: "image/jpeg")
        for (key, value) in params{
            print("key,value: \(key),\(value)")
            let stringValue = value as! String
            multipartFormData.append(stringValue.data(using: .utf8)!, withName: key)
        }
    }, to:"your url")
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                //Print progress
                print("Upload Progress: \(progress.fractionCompleted)")
            })
            upload.responseJSON { response in
                //print response.result
                print(response.result)

            }

        case .failure(let encodingError):
            print("in faulure")
            print(encodingError)
            self.presentAlertView(title: "Error", message: "cannot register", buttonText: "OK")
            //print(encodingError.description)
            break
            //print encodingError.description
        }
    }

Solution

  • If it is a UIImage you can do this

    for (key, value) in params{
    
      if let image = value as? UIImage {
          if let imageData: NSData = UIImageJPEGRepresentation(image, 1){
              multiPartFormData.appendBodyPart(data: imageData, name: "file", fileName: "key.jpg", mimeType: "image/jpg")
          }
      } else {
          multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
      }
    
    }