ios - 如何使用 Alamofire 5.0.0-beta.3 (Swift 5) 上传图片(Multipart)

标签 ios alamofire swift5

我正在使用 multipart 上传图片。此代码在 swift 4Alamofire 4 中运行良好。请为此提供任何解决方案。

public class func callsendImageAPI(param:[String: Any],arrImage:[UIImage],imageKey:String,URlName:String,controller:UIViewController, withblock:@escaping (_ response: AnyObject?)->Void){

    Alamofire.upload(multipartFormData:{ MultipartFormData in

        for (key, value) in param {
            MultipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }

        for img in arrImage {

            guard let imgData = img.jpegData(compressionQuality: 1) else { return }
            MultipartFormData.append(imgData, withName: imageKey, fileName: FuncationManager.getCurrentTimeStamp() + ".jpeg", mimeType: "image/jpeg")
        }

    },usingThreshold:UInt64.init(),
      to: "URL",
        method:.post,
        headers:["Content-type": "multipart/form-data",
                 "Content-Disposition" : "form-data"],
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, , ):

                upload.uploadProgress(closure: { (Progress) in
                    print("Upload Progress: \(Progress.fractionCompleted)")
                })

                upload.responseJSON { response in
                    switch(response.result) {
                    case .success(_):
                        let dic = response.result.value as! NSDictionary
                        if (dic.object(forKey:  "status")! as! Int == 1){
                            withblock(dic.object(forKey: "data") as AnyObject)
                        }else if (dic.object(forKey: Message.Status)! as! Int == 2){
                            print("error message")

                        }else{
                            print("error message")
                        }
                    case .failure(_):
                        print("error message")
                    }
                }

            case .failure(let encodingError):
                print("error message")
            }
    })}

提前致谢。

最佳答案

Almofire 5.0 和 Swift 5.0

    //Set Your URL
    let api_url = "YOUR URL"
    guard let url = URL(string: api_url) else {
        return
    }

    var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0 * 1000)
    urlRequest.httpMethod = "POST"
    urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")

    //Set Your Parameter
    let parameterDict = NSMutableDictionary()
    parameterDict.setValue(self.name, forKey: "name")

    //Set Image Data
    let imgData = self.img_photo.image!.jpegData(compressionQuality: 0.5)!

   // Now Execute 
    AF.upload(multipartFormData: { multiPart in
        for (key, value) in parameterDict {
            if let temp = value as? String {
                multiPart.append(temp.data(using: .utf8)!, withName: key as! String)
            }
            if let temp = value as? Int {
                multiPart.append("\(temp)".data(using: .utf8)!, withName: key as! String)
            }
            if let temp = value as? NSArray {
                temp.forEach({ element in
                    let keyObj = key as! String + "[]"
                    if let string = element as? String {
                        multiPart.append(string.data(using: .utf8)!, withName: keyObj)
                    } else
                        if let num = element as? Int {
                            let value = "\(num)"
                            multiPart.append(value.data(using: .utf8)!, withName: keyObj)
                    }
                })
            }
        }
        multiPart.append(imgData, withName: "file", fileName: "file.png", mimeType: "image/png")
    }, with: urlRequest)
        .uploadProgress(queue: .main, closure: { progress in
            //Current upload progress of file
            print("Upload Progress: \(progress.fractionCompleted)")
        })
        .responseJSON(completionHandler: { data in

                   switch data.result {

                   case .success(_):
                    do {
                    
                    let dictionary = try JSONSerialization.jsonObject(with: data.data!, options: .fragmentsAllowed) as! NSDictionary
                      
                        print("Success!")
                        print(dictionary)
                   }
                   catch {
                      // catch error.
                    print("catch error")

                          }
                    break
                        
                   case .failure(_):
                    print("failure")

                    break
                    
                }


        })

很高兴为您提供帮助:)

对我有用

关于ios - 如何使用 Alamofire 5.0.0-beta.3 (Swift 5) 上传图片(Multipart),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55626235/

相关文章:

ios 检查用户是否登录到 icloud,如果没有则将用户发送到设置

ios - 带有嵌入库的 Cocoa Touch Framework Swift

swift - "Implicitly unwrapped property"警告?

ios - 为 Alamofire 全局设置超时间隔

ios - Swift 5 应用程序是否只能在特定的 iOS 版本上运行?

SwiftUI 发布的变量未更新

ios - 如何快速调整导航项目栏中的图像图标?

ios - Xcode 7.1中的iOS的Crashlytics,在xcode 7中添加框架后引发多个错误

ios - 我应该使用数组还是数据库——在哪里初始化它?

json - 如何为以下 JSON 数据创建模型类并解析它?