gpt4 book ai didi

ios - Json解析错误: use of undeclared type 'Foundation' in Swift iOS

转载 作者:行者123 更新时间:2023-11-28 14:09:47 25 4
gpt4 key购买 nike

我正在使用 Swift 创建一个应用程序,我必须在其中显示使用以下 URL 的国家/地区列表:

https://restcountries.eu/rest/v2/all

在这里,我只需要获取 name 键并添加到我的 NSMutableArray 中。当我尝试使用 URLSession 解析它时,出现错误:

expression produced error: error: /var/folders/_3/27lhgzw9699c4_yg37r72_d80000gp/T/expr40-bcf47d..swift:1:65: error: use of undeclared type 'Foundation'
Swift._DebuggerSupport.stringForPrintObject(Swift.UnsafePointer<Foundation.Data>(bitPattern: 0x105c0c2f0)!.pointee)

下面是我的代码:

func fetchCountryList(countryURL:URL, completion:@escaping (NSDictionary) -> ()) {

print(countryURL)

let request = NSMutableURLRequest( url: countryURL as URL)

let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
do{
if let data = data,
let jsonString = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
, error == nil {
completion(jsonString)
} else {
print("error=\(error!.localizedDescription)")
let errorDict = ["error_status":true,"message":error!.localizedDescription] as [String : Any]
completion(errorDict as NSDictionary)

}
}
catch{
print("error=\(error.localizedDescription)")
let errorDict = ["error_status":true,"message":error.localizedDescription] as [String : Any]
completion(errorDict as NSDictionary)

}

}
task.resume()
}

任何人都可以在这里告诉我我的错误。提前致谢!

最佳答案

替换

try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary

try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [[String: Any]]

因为它是一个对象数组,我们还需要将 json 转换为 array

要获取国家名称数组,我们可以通过以下方式实现:

guard let countries = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [[String: Any]] else {
return
}
let countryNames = countries.map { $0["name"] as! String }

关于ios - Json解析错误: use of undeclared type 'Foundation' in Swift iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52680976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com