1

我正在尝试将图像上传到服务器,它工作正常,但有时我在下面的代码中的 try 语句中收到错误。这就是错误所说的

致命错误:“试试!” 表达式意外引发错误:错误域 = NSCocoaErrorDomain 代码 = 3840“字符 0 周围的值无效。” UserInfo={NSDebugDescription=字符 0.} 周围的值无效:文件 /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)

            }

        })

     }
4

1 回答 1

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;
}

希望这会有所帮助。

于 2016-02-06T19:38:11.340 回答