简体   繁体   中英

Extra argument 'error' in call - Unable to build my Xcode project

import Foundation

class NetworkOperation {

    lazy var config: NSURLSessionConfiguration =     NSURLSessionConfiguration.defaultSessionConfiguration()
    lazy var session: NSURLSession = NSURLSession(configuration: self.config)
    let queryURL: NSURL

    typealias JSONDictionaryCompletion = ([String: AnyObject]? -> Void)

    init(url: NSURL) {
        self.queryURL = url
    }

    func downloadJSONFromURL(completion: JSONDictionaryCompletion) {

        let request = NSURLRequest(URL: queryURL)
        let dataTask = session.dataTaskWithRequest(request) {
            (let data, let response, let error) in

// 1. Check HTTP response for successful GET request

            if let httpResponse = response as? NSHTTPURLResponse {
                switch httpResponse.statusCode {
                case 200:

// 2. Create JSON object with data

                    let jsonDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
                    completion(jsonDictionary)
                default:
                    print("GET request not successful. HTTP status code: \(httpResponse.statusCode)")
                }
            } else {
                print("Error: Not a valid HTTP response")
            }
        }

        dataTask.resume()
    }
}

In the 'Create JSON object with data' step, I keep receiving the "extra argument 'error' in call". What is happening? I am unable to find documentation to help me further in this.

You can do it by this way.

do{
        var jsonDictionary  = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers)
        //completion(jsonDictionary)
    }catch{
       // report error
    }

at the top of step 2: creating json....

add this line:

var err: NSError?

// 1. Check HTTP response for successful GET request

            if let httpResponse = response as? NSHTTPURLResponse {
                switch httpResponse.statusCode {
                case 200:

// 2. Create JSON object with data

                    let jsonDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? [String: AnyObject]
                    completion(jsonDictionary)
                default:
                    println("GET request not successful. HTTP status code: \(httpResponse.statusCode)")
                }
            } else {
                println("Error: Not a valid HTTP response")
            }
        }

        dataTask.resume()
    }
}

Finally figured it out! Thank you for your input everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM