我正在尝试使用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'
答案 0 :(得分:3)
您在返回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)
}
}