[英]Alamofire .responseJSON doesn't work with JSON response
我正在使用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)
有什么幫助嗎? 提前致謝!
嘗試替換成功塊:-
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!)
})
}
在獲取價值之前,請檢查您的結果是失敗還是成功。 例如:
switch response.result {
case .Success(let value):
print("Value: \(value)")
break
case .Failure(let error):
print("Error: \(error)")
break
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.