【问题标题】:How to get data to return from NSURLSessionDataTask in Swift如何在 Swift 中获取数据以从 NSURLSessionDataTask 返回
【发布时间】:2015-01-03 20:36:23
【问题描述】:

我有同样的问题,在这里被问和回答:How to get data to return from 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()
}

我想我想要一种从原始 all 传入完成处理程序的方法,或者使用类似于 C# 5 的方式使用异步任务来等待结果..

任何帮助表示赞赏..

【问题讨论】:

    标签: swift completionhandler nsurlsessiontask


    【解决方案1】:

    您可以将此框架用于 Swift 协程 - https://github.com/belozierov/SwiftCoroutine

    DispatchQueue.main.startCoroutine {
        let dataFuture = URLSession.shared.dataTaskFuture(for: url)
        let data = try dataFuture.await().data
        . . . parse data ...
    }
    

    【讨论】:

      【解决方案2】:

      在来自 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
      }
      

      【讨论】:

        【解决方案3】:

        更改您的 GetHomeData() 方法,使其占用一个块。当您调用该方法时,将它传递给您想要对数据执行什么操作的块。在数据任务的完成块中,调用这个传入的块。

        【讨论】:

        • 嗨,我已将我的 GetHome 乐趣更改为 :func GetHomeData(completionHandler: ((NSDictionary!) -> Void)?) -> NSDictionary 然后调用该函数:让结果:NSDictionary = homeModel。 GetHomeData({(jsonResult) in // 使用结果 }); ...但是在返回结果时,我在 GetHomeData 函数中遇到异常。你能举个例子吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-11
        • 1970-01-01
        • 1970-01-01
        • 2012-12-30
        • 1970-01-01
        • 2019-06-24
        相关资源
        最近更新 更多