1)我有以下内容:
- 供用户输入一些数据(例如用户名)的文本字段
-添加了一个activityIndicator
2)当用户按下键盘的“Return”或“Go”或“Done”键时,它将调用 SendPostRequest 函数,如下代码。
代码没有编译错误。
在 URLSession 内导航是否有任何问题?
问题:
以 NSException 类型的未捕获异常终止
func textFieldShouldReturn( _ textField: UITextField) -> Bool {
ActivityIndicator.startAnimating()
SendPostRequest()
}
unc SendPostRequest(user: String ) {
let Url = String(format: "your url")
guard let serviceUrl = URL(string: Url) else { return }
let parameterDictionary = ["username" : "User1"]
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
return
}
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
//condition met:
let jsonStatus: String! = json["Status"] as String
if jsonStatus == "Code123"
self.myActivityIndicator.stopAnimating()
self.performSegue(withIdentifier:"SegueAcct",sender: self )
}catch {
print(error)
}
}
}.resume()
}
最佳答案
我认为问题在于完成 block 中的代码是在后台线程上运行的,所以只需像这样在主线程上发布 performSegue
DispatchQueue.main.async {
self.myActivityIndicator.stopAnimating()
self.performSegue(withIdentifier:"SegueAcct",sender: self )
}
关于ios - 从 URLsession 解析 Json 时如何导航到其他 Viewcontroller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46785808/