【问题标题】:Calling another ViewController give error - UI API called on a background thread调用另一个 ViewController 会出错 - 在后台线程上调用 UI API
【发布时间】:2019-11-07 10:06:27
【问题描述】:

我是 IOS 新手,速度很快。我有登录的应用程序。在登录按钮单击时,我正在使用 post 方法检查用户名和密码。但是在成功的结果上我想去新的视图控制器,但它给了我错误在后台线程上调用 UI API 按钮点击代码如下。 swift中是否有类似android的asynctask onPostExecute,然后告诉我。 感谢您的帮助。

@IBAction func chkbt(_ sender: Any) {

        var url = URL(string: "http://www.miappserver.co.in:8079/chs_server/rest/menuService/getLoginDetails")!

        var request = URLRequest(url: url)

        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        request.httpMethod = "POST"

        let postString = "{\"one\":\"*userid*\",\"two\":\"*password*\",\"three\":\"strimg\",\"authApiKey\":\"zpfkenaojjawlwjnbsoej-fhfbs\"}"; // which is your parameters

        let idString : String = txtUserId.text!

        let passString : String = txtPassword.text!

        let newString1 = postString.replacingOccurrences(of: "*userid*", with: idString, options: .literal, range: nil)

        let newString2 = newString1.replacingOccurrences(of: "*password*", with: passString, options: .literal, range: nil)

        request.httpBody = newString2.data(using: .utf8)

        // Getting response for POST Method

        DispatchQueue.main.async {

            let task = URLSession.shared.dataTask(with: request) { data, response, error in

                guard let data = data, error == nil else {

                    return // check for fundamental networking error

                }

                // Getting values from JSON Response

                let responseString = String(data: data, encoding: .utf8)

                self.parseJSON(data)

                var users = [Meal]()

                do{

                    users = try JSONDecoder().decode(Array<Meal>.self, from: data)

                    print(users.first?.userId)

                    //print(users.first?.userPersonName)

                    if users.first?.userId != nil {

                        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

                        let newViewController = storyBoard.instantiateViewController(withIdentifier: "Dashboard") as! Dashboard

                        self.present(newViewController, animated: true, completion: nil)

                    }
                }catch{
                    print(error)
                }
                //print("responseString = \(String(describing: responseString))")
                //print(responseString)

                do {

                    let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? NSDictionary

                }catch _ {

                    print ("OOps not good JSON formatted response")

                }

            }

            task.resume()

        }

    }


【问题讨论】:

    标签: ios swift http user-interface url


    【解决方案1】:

    你需要

    DispatchQueue.main.async {  
       self.storyBoard!.instantiateViewController(withIdentifier: "Dashboard") as! Dashboard 
       self.present(newViewController, animated: true, completion: nil) 
    }
    

    由于URLSession.shared.dataTask(with: request) 在后台线程中运行,无论您是否用DispatchQueue.main.async { 包围它


    @IBAction func chkbt(_ sender: Any) {
    
            var url = URL(string: "http://www.miappserver.co.in:8079/chs_server/rest/menuService/getLoginDetails")!
    
            var request = URLRequest(url: url)
    
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
            request.httpMethod = "POST"
    
            let postString = "{\"one\":\"*userid*\",\"two\":\"*password*\",\"three\":\"strimg\",\"authApiKey\":\"zpfkenaojjawlwjnbsoej-fhfbs\"}"; // which is your parameters
    
            let idString : String = txtUserId.text!
    
            let passString : String = txtPassword.text!
    
            let newString1 = postString.replacingOccurrences(of: "*userid*", with: idString, options: .literal, range: nil)
    
            let newString2 = newString1.replacingOccurrences(of: "*password*", with: passString, options: .literal, range: nil)
    
            request.httpBody = newString2.data(using: .utf8)
    
            // Getting response for POST Method
    
                let task = URLSession.shared.dataTask(with: request) { data, response, error in
    
                    guard let data = data, error == nil else {
    
                        return // check for fundamental networking error
    
                    }
    
                    // Getting values from JSON Response
    
                    let responseString = String(data: data, encoding: .utf8)
    
                    self.parseJSON(data)
    
                    var users = [Meal]()
    
                    do{
    
                        users = try JSONDecoder().decode(Array<Meal>.self, from: data)
    
                        print(users.first?.userId)
    
                        //print(users.first?.userPersonName)
    
                        if users.first?.userId != nil {
    
                           DispatchQueue.main.async {  
    
                            self.storyBoard!.instantiateViewController(withIdentifier: "Dashboard") as! Dashboard 
    
                            self.present(newViewController, animated: true, completion: nil) 
                          }
    
                        }
                    }catch{
                        print(error)
                    }
                    //print("responseString = \(String(describing: responseString))")
                    //print(responseString)
    
                    do {
    
                        let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? NSDictionary
    
                    }catch _ {
    
                        print ("OOps not good JSON formatted response")
    
                    }
    
                }
    
                task.resume()
    
        }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 2018-01-07
      • 2017-11-29
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多