Search code examples
swiftswift3

Cannot invoke 'jsonObject' with an argument list of type


When using this code to get JSON from a server with Basic auth:

                    let config = URLSessionConfiguration.default
        let userPasswordData = "\(username!):\(password!)".data(using: .utf8)
        let base64EncodedCredential = userPasswordData!.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
        let authString = "Basic \(base64EncodedCredential)"
        config.httpAdditionalHeaders = ["Authorization" : authString]
        let session = URLSession(configuration: config)

        let url = URL(string: "https://theforest.academy/api/v1/auth")
        let task = session.dataTask(with: url!) {
            (data, response, error) in
            if (response as? HTTPURLResponse) != nil {


                do {
                    if let data = data {
                       // let json1 = try JSONSerialization.jsonObject(with: data) as? [String: Any]
                        let json = try JSONSerialization.jsonObject(with: data, options: [], error: []) as? [String: Any]
                        if(json["valid"]) {
                            print(json["token"])
                        } else {
                            print("Invalid login")
                        }
                    }
                } catch {
                    print("Error deserializing JSON: \(error)")
                }

I am getting the following error

Cannot invoke 'jsonObject' with an argument list of type '(with: Data, options: [Any], error: [Any])'


Solution

  • Looking at the documentation, it seems that you only have two choices:

    jsonObject(with: Data, options: JSONSerialization.ReadingOptions = [])
    

    And

    jsonObject(with: InputStream, options: JSONSerialization.ReadingOptions = [])
    

    I think you are looking for the first method. Perhaps you are confusing it with

    writeJSONObject(Any, to: OutputStream, options: JSONSerialization.WritingOptions = [], error: NSErrorPointer)
    

    So, in short, such a method does not exist. That is why you are getting the error.