为什么在convertDataWithCompletionHandler函数中使用completionHandlerForConvertData闭包?

时间:2019-02-11 14:21:36

标签: ios swift completionhandler

下面是代码发出的请求,会将completionHandlerForGET传递给函数convertDataWithCompletionHandler的completementHandlerForConvertData处理程序。但是completionHandlerForConvertData似乎什么也没做。为什么使用它?

func taskForGETMethod(_ method: String, parameters: [String:AnyObject], completionHandlerForGET: @escaping (_ result: AnyObject?, _ error: NSError?) -> Void) -> URLSessionDataTask {

    /* 1. Set the parameters */
    var parametersWithApiKey = parameters
    parametersWithApiKey[ParameterKeys.ApiKey] = Constants.ApiKey as AnyObject?

    /* 2/3. Build the URL, Configure the request */
    let request = NSMutableURLRequest(url: tmdbURLFromParameters(parametersWithApiKey, withPathExtension: method))

    /* 4. Make the request */
    let task = session.dataTask(with: request as URLRequest) { (data, response, error) in

        func sendError(_ error: String) {
            print(error)
            let userInfo = [NSLocalizedDescriptionKey : error]
            completionHandlerForGET(nil, NSError(domain: "taskForGETMethod", code: 1, userInfo: userInfo))
        }

        /* GUARD: Was there an error? */
        guard (error == nil) else {
            sendError("There was an error with your request: \(error!)")
            return
        }

        /* GUARD: Did we get a successful 2XX response? */
        guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
            sendError("Your request returned a status code other than 2xx!")
            return
        }

        /* GUARD: Was there any data returned? */
        guard let data = data else {
            sendError("No data was returned by the request!")
            return
        }

        /* 5/6. Parse the data and use the data (happens in completion handler) */
        self.convertDataWithCompletionHandler(data, completionHandlerForConvertData: completionHandlerForGET)
    }

    /* 7. Start the request */
    task.resume()

    return task
}

completionHandlerForConvertData并没有执行任何操作,例如打印错误。

 private func convertDataWithCompletionHandler(_ data: Data, completionHandlerForConvertData: (_ result: AnyObject?, _ error: NSError?) -> Void) {

    var parsedResult: AnyObject! = nil
    do {
        //class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
        //Returns a Foundation object from given JSON data.

        parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject
    } catch {
        let userInfo = [NSLocalizedDescriptionKey : "Could not parse the data as JSON: '\(data)'"]
        completionHandlerForConvertData(nil, NSError(domain: "convertDataWithCompletionHandler", code: 1, userInfo: userInfo))
    }

    completionHandlerForConvertData(parsedResult, nil)
}

0 个答案:

没有答案