如何在Swift中从NSURLSessionDataTask中获取数据返回。

问题描述 投票:1回答:3

我的这个问题和这里的提问和回答一样。如何从NSURLSessionDataTask中获取数据返回。

的区别。 我如何在Swift中做到这一点? 我完全不懂Objective C,所以想解释这个答案对我来说有点徒劳......

所以给定下面的代码,我有一个FirstViewController,它将调用我的HomeModel类,使用NSURLSession调用去获取数据。 一旦调用完成,我想把数据返回给FirstViewController,这样我就可以在视图中设置它。

FirstViewController类是这样的。

import UIKit
class FirstViewController: UIViewController
{
    let homeModel = HomeModel()

    override func viewDidLoad()
    {
       super.viewDidLoad()

       // Go load the home page content
       SetHomeContent()
    }

  override func didReceiveMemoryWarning()
  {
      super.didReceiveMemoryWarning()
  }

  /*Call to go get home page content*/
  func SetHomeContent()
  {
      homeModel.GetHomeData();

      //TODO find a way to get result here... and set it to the textView
  }
}

HomeModel类看起来是这样的:

 import Foundation
 class HomeModel
 {

    private let siteContent:String = "http://www.imoc.co.nz/MobileApp/HomeContent"

   func GetHomeData()
   {
      var url : NSURL! = NSURL(string:siteContent)
      var request: NSURLRequest = NSURLRequest(URL:url)
      let config = NSURLSessionConfiguration.defaultSessionConfiguration()
      let session = NSURLSession(configuration: config)

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

        var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil

        let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: error) as? NSDictionary!

      // At this stage I want the jsonResult to be returned to the FirstViewController
    });

    // do whatever you need with the task
    task.resume()
}

我想我需要一种方法来传递一个完成处理程序 或者类似于C#5中使用异步任务来等待结果...

感谢任何帮助。

swift completionhandler nsurlsessiontask
3个回答
3
投票

在Abizern的帮助和建议下,我终于成功地写出了这个块或闭包,如果你想的话。

所以,什么工作对我来说,在最后。

我把GetHomeData函数改成了下面这个样子:

private let siteContent:String = "http://www.imoc.co.nz/MobileApp/HomeContent"
// I changed the signiture from my original question
func GetHomeData(completionHandler: ((NSDictionary!) -> Void)?)
{
    var url : NSURL! = NSURL(string:siteContent)
    var request: NSURLRequest = NSURLRequest(URL:url)
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)

    let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil

        let jsonResult: NSDictionary! =  NSJSONSerialization.JSONObjectWithData(data, options: nil, error: error) as? NSDictionary!

        // then on complete I call the completionHandler...
        completionHandler?(jsonResult?);
    });
    task.resume()
}

然后我像这样调用函数:

/*Call to go get home page content*/
func SetHomeContent()
{
    homeModel.GetHomeData(self.resultHandler)
}

func resultHandler(jsonResult:NSDictionary!)
{
    let siteContent = jsonResult.objectForKey("SiteContent") as NSDictionary
    let paraOne = siteContent.objectForKey("HomePageParagraphOne") as String
}

1
投票

改变你的GetHomeData()方法,让它接受一个块。当你调用这个方法的时候,把你想对数据做的事情的块传给它。在数据任务的完成块中,调用这个传入的块。


0
投票

你可以用这个框架来实现Swift的coroutine--。https:/github.comelozierovSwiftCoroutine。

DispatchQueue.main.startCoroutine {
    let dataFuture = URLSession.shared.dataTaskFuture(for: url)
    let data = try dataFuture.await().data
    . . . parse data ...
}
© www.soinside.com 2019 - 2024. All rights reserved.