我正在尝试将图像上传到服务器并且工作正常,但有时我在下面的代码中的try语句中收到错误。这就是错误所说的
致命错误:'试试!'表达式意外地引发了错误:错误 Domain = NSCocoaErrorDomain Code = 3840“字符周围的值无效 0.“UserInfo = {NSDebugDescription =字符0周围的值无效}}:file /Library/Caches/com.apple.xbs/Sources/swiftlang_PONDEROSA/swiftlang_PONDEROSA-700.1.101.6/src/swift/stdlib/public/core/ErrorType.swift, 第50行
func uploadImages(imageData: NSData, withParams requestDict:NSDictionary, callBack:(responseDict: NSDictionary?, error: NSError?) -> ())
{
print(requestDict)
let boundary = generateBoundaryString()
let url:NSURL = NSURL(string: String(format: "%@%@", BASE_URL, IMAGE_UPLOAD_API))!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.timeoutInterval = FLOAT_CONSTANT_60
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.HTTPBody = createBodyWithParameters(requestDict as? [String : AnyObject], filePathKey: "image", imageData: imageData, boundary: boundary)
print(requestDict)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) in
do {
let JSON = try! NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.AllowFragments)
guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
//get your JSONData here from dictionary.
return
}
callBack(responseDict: JSON as? NSDictionary, error: nil)
print("JSONDictionary! \(JSONDictionary)")
}
catch let JSONError as NSError {
print("\(JSONError)")
callBack(responseDict: nil, error: JSONError)
}
})
}
答案 0 :(得分:0)
由于我正在使用的API返回的json数据前面的一些无效字符/填充,我遇到了类似的问题。要修复它,我必须在尝试反序列化前删除前几个字符。
var parsedDictionary: NSDictionary? = nil;
do{
let loginResult = result.subdataWithRange(NSMakeRange(5, result.length - 5))
parsedDictionary = try! NSJSONSerialization.JSONObjectWithData(loginResult, options: .AllowFragments) as? NSDictionary;
}
希望这有帮助。