NSURLSession不会返回

时间:2015-10-02 12:30:52

标签: ios nsurlconnection ios9 nsurlsession

知道为什么NSURLSession完成块没有被调用?使用NSURLConnection可行,但在iOS 9中已弃用NSURLConnection

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
    }  
})

1 个答案:

答案 0 :(得分:1)

您的变量a是NSURLSessionDataTask。

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

a.resume()