ios - Alamofire 分段上传出现错误

标签 ios swift alamofire

我正在尝试使用 Alamofire 多部分表单数据将图像上传到服务器,但是在执行时我收到错误为

exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber dataUsingEncoding:]: unrecognized selector sent to instance 0x1669e250'

在行

MultipartFormData.append(((value as AnyObject).data(using: String.Encoding.utf8.rawValue))!, withName: key)

下面是我的完整代码

guard let image = selectedImage else {
        return
    }

    let heightInPixels = Int(image.size.height * image.scale)
    let widthInPixels = Int(image.size.width * image.scale)



     let parameters: Parameters = ["user_id":  Utility().getBearerToken(),"description": descriptionTextView.text ?? "",
     "lat": self.lat ?? "" , "long":self.long ?? "" ,
     "location_name": locationTextView.text ?? "" ,
     "height": heightInPixels, "width": widthInPixels];


//    let parameters: Parameters = ["user_id":  Utility().getBearerToken()];
    print(parameters)
    Alamofire.upload(multipartFormData: { MultipartFormData in
        for (key, value) in parameters {
            MultipartFormData.append(((value as AnyObject).data(using: String.Encoding.utf8.rawValue))!, withName: key)

        }

        let imgData = UIImageJPEGRepresentation(image,1)
        MultipartFormData.append(imgData!, withName: "file", fileName: "upload.jpg", mimeType: "image/jpeg")

    }, to: "http://server.com/upload.php") { (result) in
        switch result {
        case .success(let upload, _, _):
            upload.uploadProgress(closure: { (Progress) in
                print("Upload Progress: \(Progress.fractionCompleted)")
            })

            upload.responseString { response in
                print(response.result.value!)
            }       
        case .failure(let encodingError):
            print(encodingError.localizedDescription)
            break
        }
  }

我尝试使用 MultipartFormData.append(value.data(using: .utf8)!, withName: name!) 但它说 value 没有成员数据

最佳答案

尝试下面的功能,它有效。

func uploadImage(urlString : String , image : UIImage, param : [String : Any], completionHandler : @escaping ( _ result : Any?) -> ())  {

    guard let imageData = UIImageJPEGRepresentation(image, 0.5) else {
        print("Could not get JPEG representation of UIImage")
        return
    }

    Alamofire.upload(multipartFormData: { multipartFormData in
        for (key, value) in param {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
        }

        multipartFormData.append(imageData,
                                 withName: "image",
                                 fileName: "image.jpg",
                                 mimeType: "image/jpeg")
    },
                     to: urlString,
                     headers: ["Authorization": "Basic xxx"],
                     encodingCompletion: { encodingResult in

                        switch encodingResult {
                        case .success(let upload, _, _):
                            upload.uploadProgress { progress in
                            }
                            upload.validate()
                            upload.responseJSON { response in
                                completionHandler(response.result.value)
                            }
                        case .failure(let encodingError):
                            print(encodingError)
                            completionHandler(nil)
                        }
    })
}

关于ios - Alamofire 分段上传出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51924652/

相关文章:

ios - 在 Swift 中使用 Alamofire 时如何获取响应头?

ios - Alamofire 无法处理 UDP 请求吗? NSPOSIXErrorDomain 代码=47

ios - Swift 3 在时间结束前创造游戏热门

iOS Swift Today 扩展 : import class from container app?

ios - 如何将 iOS Swift 3 应用程序中的数据写入 BLE (HM-10)?

swift - Xcode8 beta 6 - 带有 completionHandler 参数的 URLSession 不起作用

ios - 如何将 "dispatch_get_main_queue()"分配给 Swift 中的常量?

ios - 从嵌套 json 数组获取数据时出现问题

ios - 在 UICollectionView 中显示错误的图像

ios - 如何根据条件设置初始 View Controller ?