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])'
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.
Looking at the documentation, it seems that you only have two choices:
And
I think you are looking for the first method. Perhaps you are confusing it with
So, in short, such a method does not exist. That is why you are getting the error.