gpt4 book ai didi

ios - Alamofire .responseJSON 不适用于 JSON 响应

转载 作者:行者123 更新时间:2023-11-29 01:02:23 25 4
gpt4 key购买 nike

我正在使用 alamofire 上传图片。这是注册 API,您可以在其中使用个人资料照片进行注册(这是我必须上传的内容)

所以我的代码是这样的(我将用另一个代码替换 print(JSON);这只是为了测试哪里出了问题)

func makeUploadRequest(url: String?) {

let imageData = NSData(data: UIImageJPEGRepresentation(self.userImage.image!, 1)!)

Alamofire.upload(.POST, url!, headers: ["Content-Type":"application/json"], multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imageData, name: "image_file_1")
}, encodingCompletion: {
encodingResult in

switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { (JSON) in
print(JSON)
}

case .Failure(let encodingError):
//Show Alert in UI
print(encodingError)
}
})
}

但是当我运行这段代码时,我遇到了这条消息:

FAILURE: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around
character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

我知道为什么会收到此消息,因为响应不是 JSON 格式。但响应实际上是 JSON

{
result: "success",
msg: "",
data: {...}
}

当我使用 URL 测试 API 时,它工作正常。

当我使用 .responseString 而不是 .responseJSON 时:它说了一些关于 ASP.NET 的事情

.响应:

(Optional(<NSMutableURLRequest: 0x7f8353217d50> { URL: url }),
Optional(<NSHTTPURLResponse: 0x7f8353099040> { URL: url }
{ status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 5136;
"Content-Type" = "text/html; charset=utf-8";
Date = "Tue, 26 Apr 2016 06:09:03 GMT";
Server = "Microsoft-IIS/7.5";
"X-AspNet-Version" = "2.0.50727";
"X-Powered-By" = "ASP.NET";
} }), Optional(<3c68746d ... 2e2d2d3e>), nil)

有什么帮助吗?提前致谢!

最佳答案

尝试替换 Success block :-

case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
AppHelper.hideLoadingSpinner()
if response.result.value is NSNull
{
print("Response nil")
}
else
{
if let JSON = response.result.value {
var mydict = NSMutableDictionary()
mydict = JSON as! NSMutableDictionary

if (self.delegate != nil){
print("response:--------------------\n %@",mydict)
}
}
else
{
print("response not converted to JSON")
}

}
upload.response(completionHandler: { (request, response, data, error) -> Void in

NSLog("upload.response : data : %@", String(data: data!, encoding: NSUTF8StringEncoding)!)
NSLog("upload.response : response : %@", response!)


})
}

关于ios - Alamofire .responseJSON 不适用于 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36856131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com