使用此代码从具有Basic身份验证的服务器获取JSON:
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)")
}
我收到以下错误
无法调用' jsonObject'使用类型'的参数列表(带: 数据,选项:[任意],错误:[任何])'
答案 0 :(得分:2)
查看documentation,您似乎只有两个选择:
jsonObject(with: Data, options: JSONSerialization.ReadingOptions = [])
和
jsonObject(with: InputStream, options: JSONSerialization.ReadingOptions = [])
我认为您正在寻找第一种方法。也许你会把它与
混淆writeJSONObject(Any, to: OutputStream, options: JSONSerialization.WritingOptions = [], error: NSErrorPointer)
因此,简而言之,这种方法并不存在。这就是你收到错误的原因。
答案 1 :(得分:0)
这是因为获取数据时我们没有处理错误。因此,我们需要安全地键入种姓数据,然后将其传递给JsonSerializer。这是代码。
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")
}