我正在尝试从我用swift编写的iOS应用程序上传图像并尝试了一些我发现的代码,但没有任何效果。
通过邮递员上传工作完美。这是Postman中请求的屏幕截图:
正如您所看到的,API期望带有JSON的PUT请求只有一个名为“avatar”的字段,然后是其中的图像。还要记住表单数据。在Headers中,我只发送令牌进行身份验证。
说这个,在Swift代码中我尝试发送asms数组只有“avatar”键和图像编码:
func uploadImage(url: String){
let httpMethod: String = "PUT"
var token = getTokenFromNSUserDefaults()
var imageDataJpeg = UIImageJPEGRepresentation(self.myImage, 0.9)
var base64StringJpeg = imageDataJpeg.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) // encode the image
var base64StringJpeg2 = imageDataJpeg.base64EncodedStringWithOptions(nil) // encode the image
var imageDataPng = UIImagePNGRepresentation(self.myImage)
var base64StringPng = imageDataPng.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) // encode the image
var base64StringPng2 = imageDataPng.base64EncodedStringWithOptions(nil) // encode the image
// API Request
self.request(httpMethod, token: token, params:["avatar":base64StringPng2], url: url) { (succeeded: Bool, msg: String) -> () in
var alert = UIAlertView(title: "Success!", message: msg, delegate: nil, cancelButtonTitle: "Okay.")
if(succeeded) {
println("Success")
}
else {
println("Fail")
}
// Move to the UI thread
dispatch_async(dispatch_get_main_queue(), { () -> Void in
})
}
}
//// API REQUEST ////
func request(httpMethod: String, token: String, params: Dictionary<String, AnyObject>, url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = httpMethod
var err: NSError?
if token != ""{
request.addValue("JWT \(token)", forHTTPHeaderField: "Authorization")
}
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
////Option 1
request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Disposition")
request.addValue("multipart/form-data", forHTTPHeaderField: "Accept")
////Option 2
//request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
//request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Disposition")
//request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var msg = "No message"
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &err)
println("JSON: \(json)")
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON1: '\(jsonStr)'")
postCompleted(succeeded: false, msg: "Error")
}
else {
self.parseJson(json!)
postCompleted(succeeded: true, msg: "Works!")
return
}
})
task.resume()
}
以下是来自服务器的日志响应,总是出现406错误消息,如下所示(不要查看“删失”网址):
Response: <NSHTTPURLResponse: 0x7f967bed1450> { URL: https://***********************/ } { status code: 406, headers {
Allow = "GET, PUT, DELETE, HEAD, OPTIONS";
Connection = "keep-alive";
"Content-Type" = "application/json";
Date = "Wed, 02 Dec 2015 18:30:13 GMT";
Server = "nginx/1.4.6 (Ubuntu)";
"Transfer-Encoding" = Identity;
Vary = Accept;
"X-Frame-Options" = SAMEORIGIN;
} }
Body: Optional()
JSON: nil
The operation couldn’t be completed. (Cocoa error 3840.)
Error could not parse JSON1: 'Optional()'
Fail
非常感谢您的帮助!
答案 0 :(得分:0)
你的&#34; params&#34;不是JSON格式 - 缺少JSON字典的花括号。