首页 > 解决方案 > 如何获得在 Alamofire 中上传 base64 图像的进度?

问题描述

有什么方法可以在 alamofire 中发布带有进度的 JSON 吗?我需要做什么我有 JSON,它有 base64 图像字符串和一些其他参数,同时请求 JSON 我需要向最终用户显示进度,所以任何人都知道如何在 Alamofire 中做到这一点?

我已经按照以下链接进行操作,但它在 Alamofire 中给了我一个语法错误?

带有进度的 Alamofire POST 请求

    let parameters: [String: AnyObject] = ["key": "value" as AnyObject]
    let mutableURLRequest = NSMutableURLRequest(url: URL(string: "url goes here")!)
    mutableURLRequest.httpMethod = "POST"

    let encodedURLRequest = try! Alamofire.URLEncoding.default.encode(mutableURLRequest as! URLRequestConvertible, with: parameters)
    let data = encodedURLRequest.httpBody!

    Alamofire.upload(mutableURLRequest, data)
        .progress { _, totalBytesRead, totalBytesExpectedToRead in
            print("ENTER .PROGRESSS")
            print("\(totalBytesRead) of \(totalBytesExpectedToRead)")
        }
        .responseJSON { _, _, mydata, _ in
            print(mydata)
    }

它给了我以下错误

无法使用类型为“(NSMutableURLRequet,数据)的参数列表调用“上传”

标签: swiftalamofire

解决方案


如果要显示进度 hud,可以使用以下代码:

 let binaryImageData = base64EncodeImage(image)
 SVProgressHUD.show() //use any progress hud
  let parameters : [String:Any] = [
            "Name" : "UserProfilePhoto",
            "Body": binaryImageData,
            "parentId": userId

   ]
   let header = ["content-type" : "application/json", "Authorization": "your token here"]
   var imageURL: URL {
            return URL(string: "Your UrlString here")
        }
   Alamofire.request(imageURL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: header).responseJSON {
            response in

            if (response.result.isSuccess){
                SVProgressHUD.dismiss()
                let result = response.result.value as? NSDictionary
            }
            else{
                SVProgressHUD.dismiss()
            }
        }
    }

推荐阅读