我正在使用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的内容
.response:
(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)
有任何帮助吗?提前谢谢!
答案 0 :(得分:1)
尝试替换成功块: -
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!)
})
}
答案 1 :(得分:0)
如果在获得值之前失败或成功,请检查结果。 E.g:
switch response.result {
case .Success(let value):
print("Value: \(value)")
break
case .Failure(let error):
print("Error: \(error)")
break
}