1
votes

I'm trying to upload an image to server and it works fine, but occasionally I receive an error at try statement in my below code. This is what the error says

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}: file /Library/Caches/com.apple.xbs/Sources/swiftlang_PONDEROSA/swiftlang_PONDEROSA-700.1.101.6/src/swift/stdlib/public/core/ErrorType.swift, line 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)

            }

        })

     }
1

1 Answers

0
votes

I ran into a similar problem due to some invalid characters / padding at the front of the json data that was returned by the API I was using. To fix it I had to strip off the first few characters before trying to deserialize it.

var parsedDictionary: NSDictionary? = nil;
do{
   let loginResult = result.subdataWithRange(NSMakeRange(5, result.length - 5))
 parsedDictionary = try! NSJSONSerialization.JSONObjectWithData(loginResult, options: .AllowFragments) as? NSDictionary;
}

Hopefully that helps.