简体   繁体   English

Swift3 关闭崩溃

[英]Swift3 closure crash

Crashing while creating an instance of URLSessionTask with the completion handlers使用完成处理程序创建 URLSessionTask 实例时崩溃

func sessionTaskPostRequest (_ urlRequest : URLRequest , responseHandler: @escaping  ResponseHandler) -> URLSessionTask {
    // 5
     let sesstionTask : URLSessionTask = networkSession.dataTask(with: urlRequest, completionHandler: { (data : Data? , urlResponse : URLResponse? , error : NSError? )     in

        var json: NSDictionary!
        do {
            json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as? NSDictionary
        } catch {
            print(error)
        }

        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(error != nil) {
            responseHandler (false , nil , error , nil)
        }
        else {
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json {
                let errorJSON = parseJSON ["Err"] as! String
                if !errorJSON.isEmpty {
                    responseHandler (false , nil , nil , errorJSON)
                }else {
                    responseHandler (true , parseJSON , nil , nil)
                }
                print("Succes: \(parseJSON)")
            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                responseHandler (false , nil , error , "Error could not parse JSON")
                print("Error could not parse JSON: \(jsonStr)")
            }
        }
    } as! (Data?, URLResponse?, Error?) -> Void)

    return sesstionTask

}

And created a type alias for response handler that returns the response JSON Object .并为返回响应 JSON Object 的响应处理程序创建了一个类型别名。 Type alias as follows输入别名如下

typealias ResponseHandler = (_ successFlag :Bool , _ data : NSDictionary? , _ errorObject : NSError? , _ errorString : String?) -> Void

Seems like Response handler is getting the Error Object as NSError which will get crashed if Error object is nil and failed to cast it to NSError似乎响应处理程序正在将错误对象作为 NSError 获取,如果错误对象为零并且无法将其转换为 NSError 则会崩溃

Error = nil and when you receive it as NSError Typecasting fails because of nil object , but the same thing is handled wisely if you don't do any typecasting Error = nil 并且当你收到它时 NSError Typecasting 由于 nil object 而失败,但是如果你不做任何类型转换,同样的事情会被明智地处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM