如何在Swift中使用NSURLSessionDataTask

时间:2014-06-04 14:58:20

标签: ios swift

有人能帮助我吗?我找不到完成语法的好例子。

var url : NSURL = NSURL.URLWithString("https://itunes.apple.com/search?term=\(searchTerm)&media=software")
var request: NSURLRequest = NSURLRequest(URL:url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession.sessionWithConfiguration(config)

NSURLSessionDataTask(session.dataTaskWithRequest(request, completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?)

谢谢!

6 个答案:

答案 0 :(得分:71)

不清楚你在问什么,但我注意到你的代码中有一些错误:

  1. 您应该使用session

  2. 创建NSURLSession(configuration: config)
  3. session.dataTaskWithRequest返回NSURLSessionDataTask,因此无需将其包含在NSURLSessionDataTask()内(也称为实例化新的NSURLSessionDataTask对象)。

    < / LI>
  4. 完成处理程序是一个闭包,下面是你如何创建特定的clousure:

    {(data : NSData!, response : NSURLResponse!, error : NSError!) in
    
        // your code
    
    }
    
  5. 这是更新后的代码:

    let url = NSURL(string: "https://itunes.apple.com/search?term=\(searchTerm)&media=software")
    let request = NSURLRequest(URL: url)
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)
    
    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
    
        // notice that I can omit the types of data, response and error
    
        // your code
    
    });
    
    // do whatever you need with the task e.g. run
    task.resume()
    

答案 1 :(得分:12)

如果您在完成语法方面遇到问题,可以在调用dataTaskWithRequest(..)之前创建完成函数以使其更清晰

func handler (data: NSData!, response: NSURLResponse!, error: NSError!) {
            //handle what you need
        }

session.dataTaskWithRequest(request, completionHandler: handler)

答案 2 :(得分:5)

您也可以通过以下方式使用它: -

let url = "api url"

let nsURL = NSURL

let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) {
(data, response, error) in
   // your condition on success and failure
}

task.resume()

答案 3 :(得分:2)

更新了@fitmonk的Swift 3代码:

do {
    var request = URLRequest(url: URL(string: "https://www.example.com/api/v1")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)

    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: request, completionHandler: {(data, response, error) in

         if error != nil {

              print(error!.localizedDescription)

         }

         else {
              print(response)
         }
     })

    task.resume()
}

catch {
// handle the error
}

答案 4 :(得分:0)

session.dataTaskWithRequest(request, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) in 
    //code
)}

希望Xcode会更新以支持这些的自动完成,因为语法有点棘手,并且当这样使用时,Swift似乎不支持声明返回类型。

答案 5 :(得分:0)

Swift 4.2

    let url = URL(string: "http://url.com")!
    let request = URLRequest(url: url)
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
        print(String(data: data!, encoding: .utf8)!)
    });

    task.resume()