首页 文章

swift http请求崩溃nil值

提问于
浏览
-2

我使用以下代码从php页面检索响应 . 它的工作正常,除了每隔一段时间它在接收到以下行的零值后崩溃并出现错误:

let responseString = NSString(data:data!,encoding:String.Encoding.utf8.rawValue)

有没有办法可以 grab 这个?

let myUrl = NSURL(string: "https://*****backend/newmessage.php")
        let request = NSMutableURLRequest(url: myUrl! as URL)
        request.httpMethod = "POST"
        let postString = "userid=\(userid!)"
        
        print(postString)
        request.httpBody = postString.data(using: String.Encoding.utf8)
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
            DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
                let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                if error != nil {
                    print("Error: \(error)")
                }
                DispatchQueue.main.async() {
                    
                    print(responseString!)
                    
                    if (responseString! == "NEW"){
                        
                        self.messageIcon.setImage(UIImage(named: "newmessage.png"), for: UIControlState.normal)
                        
                    }else{
                        
                        
                        self.messageIcon.setImage(UIImage(named: "envelope.png"), for: UIControlState.normal)
                        
                        
                    }
                    
                    
                }
            }
        }
        task.resume()

1 回答

  • 1

    为什么不用 if-else 声明来解决潜在的问题呢?或者,您可以使用 guard 语句 .

    if responseString != nil { // do stuff } else { // do other stuff}

相关问题