0

我正在尝试使用 Swift 中的完成处理程序创建自己的方法:

func callURL(url: NSURL, username: String, password: String, completionHandler: (NSData?) -> ()?) {
    let request = NSMutableURLRequest(URL: url)
    let un = username
    let pass = password
    let loginString = NSString(format: "%@:%@", un, pass)
    let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
    let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0))
    request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
    completionHandler(NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
        return data
    })
}

但是我在完成处理程序行上收到错误:

'Void' is not convertible to 'NSData'
4

1 回答 1

3

您正在返回NSData一个函数Void(NSURLConnection 回调)。

您应该在 NSURLConnection 回调中调用 completionHandler:

func callURL(url: NSURL, username: String, password: String, completionHandler: ((NSData?) -> Void)?) {
    let request = NSMutableURLRequest(URL: url)
    let un = username
    let pass = password
    let loginString = NSString(format: "%@:%@", un, pass)
    let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
    let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0))
    request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
        response, data, error in
        if let completion = completionHandler {
            completion(data)
        }
    }
于 2014-10-07T15:26:53.627 回答