SWIFT:错误EXC_BAD_INSTRUCTION

时间:2017-02-24 10:24:03

标签: ios swift

运行我的应用并尝试注册用户后出现以下错误:

  

线程1:EXC_BAD_INSTRUCTION(代码= EXC_l386_INVOP,s子代码= 0x0)

这出现在代码的末尾:

  

} as! (数据?,URLResponse?,错误?) - >无效)

  let myUrl = NSURL(string: "http://127.0.0.1/MySQL_PHP/userRegister.php")
        var request = URLRequest(url: myUrl as! URL)
        request.httpMethod = "POST"
      //  let config = URLSessionConfiguration.default
        let session = URLSession.shared

        let postString = "email=\(userEmail)&passwort=\(userPasswort)&vorname=\(userVorname)&nachname=\(userName)&benutzer=\(userBenutzer)"
        request.httpBody = postString.data(using: String.Encoding.utf8)



        let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
            if error != nil {
                print("error=\(error)")
                return
            }



            var err: NSError?
            var json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

            if let parseJSON = json {
                var resultValue = parseJSON["status"] as? String
                print("result: \(resultValue)")

                var isUserRegistered: Bool = false
                if (resultValue == "Success") {
                    isUserRegistered = true
                }

                var messageToDisplay: String = parseJSON["message"] as! String!
                if (!isUserRegistered){
                    messageToDisplay = parseJSON["message"] as! String!
                }
                DispatchQueue.main.async(execute:  {

                    var myAlert = UIAlertController(title:"Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.alert)

                    let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default){
                        action in
                        self.dismiss(animated: true, completion: nil)
                    }
                    myAlert.addAction(okAction)
                    self.present(myAlert, animated: true, completion: nil)

                })
            }
        } as! (Data?, URLResponse?, Error?) -> Void )

        task.resume()

1 个答案:

答案 0 :(得分:2)

该错误具有误导性。它与数据任务关闭没有直接关系。

首先不要施放

Album.objects.filter(tracks__isnull=True)
使用尾随闭包语法

甚至更短:

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

...

})

发生错误是因为let task = session.dataTask(with: request) { (data, response, error) in ... } 周围缺少do - catch

通过添加try JSONSerialization块或使用do - catch

,错误消失了

最后有一个建议:请不要在Swift中使用try!。你正在与强大的类型系统作斗争。