NSURLSession 没有 return

NSURLSession does not return

知道为什么 NSURLSession 完成块没有被调用吗?使用 NSURLConnection 它可以工作,但 NSURLConnection 在 iOS 9.

中已弃用
let username = "8r6nibK8Pe28WFhjTX1gGb1Rhhhc7xM02v7XKRPedL4"
let password = "8r6nibK8Pe28WFhjTX1gGb1Rhhhc7xM02v7XKRPedL4"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

// create the request
let url = NSURL(string: "https://api.datamarket.azure.com/Bing/Search/Image?$format=json&Query='Rambo'+'Oscar'")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

let a = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()).dataTaskWithRequest(request, completionHandler: {data, urlResponse, error in

    if data != nil {

        let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print(str)
    } else {
        _ = 7
    }  
})

您的变量 a 是一个 NSURLSessionDataTask。

但你只是在创造它。一旦你拥有它,你实际上需要 运行 它与:

a.resume()