Search code examples
iosjsonswiftswift2nsjsonserialization

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.


Solution

  • // 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!