Cannot invoke 'jsonObject' with an argumen

2019-09-14 07:57发布

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])'

标签: swift swift3
2条回答
相关推荐>>
2楼-- · 2019-09-14 08:02

This is because we are not handling error while getting Data. So we need to safely type caste data and then pass it to JsonSerializer. Here is the code.

    do {
        let data = try NSData.init(contentsOfFile: path) as Data
        let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
        print(jsonArray)
    } catch {
        print("Error getting data")
    }
查看更多
Summer. ? 凉城
3楼-- · 2019-09-14 08:24

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.

查看更多
登录 后发表回答