将Postman中的post方法与参数和body-raw复制到Alamofire中

时间:2017-09-06 03:22:11

标签: ios swift3 alamofire

我在使用Alamofire时遇到了问题。当我尝试使用诸如 function startUpload(){ .. return true; } function stopUpload(success){ var result = ''; if (success == 1){ .. //get data from php } else { .. } return true; } 之类的通用参数发布请求时,它总是成功。但是,当我尝试使用需要参数的web服务和base64字符串的body-raw时,我无法从服务器获得成功的响应。虽然我使用Postman时成功了。有谁知道如何在Alamofire 4上做到这一点?这是我的邮递员的截图。

postman screenshot

谢谢!

2 个答案:

答案 0 :(得分:0)

@ nathan-这是我使用的代码。我只是假设“let paramsDict”中的base64String有一个名为“data”的键值,尽管它在postman中没有键名。

let urlString = ApiManager.sharedInstance.formsURL + ApiManager.sharedInstance.mobileFormsImageUpload
        let paramsDict = ["token": token, "fileID":"2", "filename":"images.png", "data": base64String] as [String : Any]

        Alamofire.request(urlString, method: .post, parameters: paramsDict, encoding: URLEncoding.httpBody, headers: [:])
            .responseJSON{ response in

                switch response.result {
                case .success(let data):

                    debugPrint("SUCCESS")


                case .failure(let error):
                    debugPrint("Request Error")

                }
        }

答案 1 :(得分:0)

我已经明白了。它需要自定义编码才能使其正常工作。必须使用url内联所有参数,因此参数内的base64字符串是唯一要编码的字符串。这是我使用的代码。

struct CustomPostEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
    var request = try URLEncoding().encode(urlRequest, with: parameters)

    let base64 = parameters?["data"] as! String
    let finalBase64Format = "\"" + base64 + "\""
    let postData = NSData(data: finalBase64Format.data(using: String.Encoding.utf8)!)
    request.httpBody = postData as Data
    return request
}
}

func uploadImageBase64(){


    let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
    if let base64String = UIImageJPEGRepresentation(testIMG, jpegCompressionQuality)?.base64EncodedString() {

        var token = String()
        if let data = UserDefaults.standard.data(forKey: "userProfile"),
            let user = NSKeyedUnarchiver.unarchiveObject(with: data) as? UserProfile{
            token = user.token
        } else {
            print("There is an issue")
        }

        let headers = [
            "content-Type": "application/json"
        ]
        let urlString = "http://localhost/FormsService.svc/Getbase64?filename=test.png&fileID=1151&token=80977580xxx"
        let paramsDict = ["data": base64String] as [String : Any]
        Alamofire.request(urlString, method: .post, parameters: paramsDict, encoding: CustomPostEncoding(), headers: headers)

            .responseJSON{ response in
                print("response JSON \(response.result)")
        }
            .response{ response in
                print("RESPONSE \(response)")
        }

    }
}