【问题标题】:Alamofire multipartFormData using [String : Any] parametersAlamofire multipartFormData 使用 [String : Any] 参数
【发布时间】:2020-03-18 13:24:42
【问题描述】:

您好,我正在尝试发布参数和/或图像。 我的参数是带有字符串、日期、整数、值的 [String : Any]。 当我只发布一个参数时,我使用 URLEncoding.default 编码。但是,当我需要同时发布参数和图像时,我使用 multipartFormData。 我的代码在下面

if url == ""{

            AF.upload(multipartFormData: { multipartFormData in
                for (key,value) in parameters {
                    multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
                }

                let jpegData = art!.jpegData(compressionQuality: 1.0)
                multipartFormData.append(Data((jpegData)!), withName: "photo")

            }, to: "\(NetworkManager.rootURL)/api/add/")
                .responseJSON { response in
                    debugPrint(response)
            }
        }else{
            AF.request("\(NetworkManager.rootURL)/api/add/", method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).response { (reponse) in
                let status = reponse.response!.statusCode
                if status == 200{
                    completion(200)
                }else{
                    completion(401)
                }
            }
        }

我的问题是,因为我的参数是带有字符串日期 int 值的任何参数,所以我得到一个 Could not cast value of type 'Swift.Int' (0x1c3f1f1e8) to 'Swift.String' (0x1c3f21390). 有什么解决方法吗?还是我必须将所有内容都更改为字符串...

感谢任何帮助

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    您需要将任何值作为 String 进行路径才能使其正常工作,因为这是将其传输到 Data 的唯一方法,其他一些人使用

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

    【讨论】:

    • 您好,谢谢您的回答。我尝试了上面的代码并得到了Type 'UInt' has no member 'utf8'
    • 如果上述方法不起作用,您必须遵循所有字符串值
    【解决方案2】:

    我已经为使用 Multipart 将带有参数的图像上传到服务器制作了块功能

    //Here strUrl = YOUR WEBSERVICE URL
    //postParam = post Request parameter i.e. 
    //let postParam : [String : Any] = [first_name : "name"]
    //imageArray = image upload array i.e.
    //var imageArray : [[String:Data]] = [["image_name" : YOUR IMAGE DATA]]
    
    func postImageRequestWithURL(withUrl strURL: String,withParam postParam: Dictionary<String, Any>,withImages imageArray:[[String:Data]], completion:@escaping (_ isSuccess: Bool, _ response:NSDictionary) -> Void)
    {
       let requetURL = strURL
    
       Alamofire.upload(multipartFormData: { (MultipartFormData) in
    
        for (imageDic) in imageArray
        {
            for (key,value) in imageDic
            {
                MultipartFormData.append(value, withName:key,fileName: "file.jpg", mimeType: "image/jpg")
            }
        }
    
        for (key, value) in postParam
        {
            MultipartFormData.append("\(value)".data(using: .utf8)!, withName: key)
    
          // MultipartFormData.append(value, withName: key)
        }
    
    }, usingThreshold: UInt64.init(), to: requetURL, method: .post, headers: ["Accept": "application/json"]) { (result) in
    
        switch result {
        case .success(let upload, _, _):
    
            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })
    
            upload.responseJSON { response in
    
                let desiredString = NSString(data: response.data!, encoding: String.Encoding.utf8.rawValue)
    
                print("Response ====================")
    
                print(desiredString!)
    
                if let json = response.result.value as? NSDictionary
                {
                    if response.response?.statusCode == 200
                        || response.response?.statusCode == 201
                        || response.response?.statusCode == 202
                    {
                        completion(true,json);
                    }
                    else
                    {
                        completion(false,json);
                    }
                }
                else
                {
                    completion(false,[:]);
                }
            }
    
        case .failure(let encodingError):
            print(encodingError)
    
            completion(false,[:]);
        }
    
      }
    }
    

    你也可以使用这个上传多张图片 我希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-17
      • 1970-01-01
      • 2017-11-23
      • 2015-11-04
      • 2020-12-27
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多