【问题标题】:Fatal error Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0 while uploading image in swift致命错误 Error Domain=NSCocoaErrorDomain Code=3840 “快速上传图片时字符 0 周围的值无效
【发布时间】:2016-04-13 05:30:00
【问题描述】:

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

致命错误:“试试!”表达式意外引发错误:错误 Domain=NSCocoaErrorDomain Code=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)

            }

        })

     }

【问题讨论】:

    标签: ios json swift2 image-upload xcode7.1


    【解决方案1】:

    由于我使用的 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-08-28
      • 2017-06-24
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      相关资源
      最近更新 更多