在从URLsession解析Json时如何导航到其他Viewcontroller

时间:2017-10-17 08:31:30

标签: ios swift3

1)我有以下内容:
- 一个textField,供用户输入一些数据,如用户名
- 添加了activityIndi​​cator

2)当用户点击键盘后返回'或者' Go'或者'完成'键,它将调用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()
    }

1 个答案:

答案 0 :(得分:1)

我认为问题是完成块中的代码在后台线程上运行,所以只需在主线程上发布performSegue就好了

DispatchQueue.main.async {
    self.myActivityIndicator.stopAnimating()

    self.performSegue(withIdentifier:"SegueAcct",sender: self )
}