我正在尝试使用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'
最佳答案
您正在返回NSData
的函数(NSURLConnection回调)中返回Void
。
您应该像这样在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)
}
}