提问人:emsiloader 提问时间:4/18/2021 更新时间:4/18/2021 访问量:436
在 Swift 的 textview 中显示 REST API 结果不起作用
display the REST API result in textview in Swift doesn't work
问:
我正在尝试开发一个函数来连接和读取 REST API,然后在文本视图中显示返回的 json,代码如下:
func restapiRead()
{
var request = URLRequest(url: URL(string: "https://reqres.in/api/users?page=1")!)
request.httpMethod = "GET"
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
print(response!)
do {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
print(json)
self.mytv.text = "\(json as! [[String: AnyObject]])" //> code line 1
self.mytv.text = "\(json as! NSArray)" //> code line 2
}
catch {
print("error")
}
})
task.resume()
}
实际上上面的所有代码都没有任何错误,但是然后我使用 codeline1 或 codeline2 将结果复制到 textview 中,它会发出“警告”消息警告:
从 '[String : AnyObject]' 强制转换为不相关类型 '[[String : AnyObject]]' 总是失败
如果我运行忽略警告并运行,我会在 codeline1(以及 2)处收到以下错误:
线程 6:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)
如何在 textview 中将结果复制为原始 json?
谢谢
答:
0赞
hoseinali alborzi
4/18/2021
#1
您应该将 JSON 转换为字符串以使用 textView 。
json.description
测试 100% 正常
代码更改为:
func restapiRead()
{
var request = URLRequest(url: URL(string: "https://reqres.in/api/users?page=1")!)
request.httpMethod = "GET"
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
print(response!)
do {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
DispatchQueue.main.async {
self.mytv.text = json.description
}
}
catch {
print("error")
}
})
task.resume()
}
评论
DispatchQueue.main.async {...}