在方法A中,从方法B中的回调中获取数据?

时间:2017-09-01 15:41:13

标签: swift callback

我有一个构建函数来从API获取最新的项目。还有其他几个功能不同,但它们的工作方式相同。它看起来像这样:

func getLatest(pageNumber: Int) -> Array<Any>{
    let urlRequest = URL(string: baseUrl + latestUrl + String(pageNumber))

    let requestedData = doRequest(url: urlRequest!, completion: { data -> Void in
        // We have the data from doRequest stored in data, but now what?!

    })

    return allData
}

我还有一个处理请求的异步方法。那个看起来像这样:

func doRequest(url: URL, completion: @escaping ([[ApiItem]]) -> ()){
    var allItems = [[ApiItem]]()

    URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else { return }

        do{
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: AnyObject]

            let results = json["items"] as? [AnyObject]

            for r in results!{
                let item = ApiItem(json: r as! [String: Any])

                allItems.append([item])
            }

            completion(allItems)
        } catch let jsonError{
            print("JSON error: \(jsonError)")
        }
    }.resume()

doRequest函数绝对正常。它获取数据,解析JSON并将其发送回getLatest - &gt; requestedData。现在的问题是,getLatest()需要的函数,用于返回data requestedData变量中存储的数据。

我怎样才能这样做,getLatest()函数返回datarequestedData()中存储的数据?

2 个答案:

答案 0 :(得分:0)

所以我通过这样做来修复它:

在第一种方法中,实际需要来自API的数据,我添加了这个:

getLatest()

func getLatest(pageNumber: Int, completion: @escaping ([ApiItem]) -> ()) { let urlRequest = URL(string: baseUrl + trendingUrl + String(pageNumber)) let requestedData = doRequest(url: urlRequest!, completion: { data -> Void in // We have the data from doRequest stored in data var requestedData = data completion(requestedData) }) } 方法如下所示:

doRequest()

最后,func doRequest(url: URL, completion: @escaping ([ApiItem]) -> ()){ var allItems = [ApiItem]() URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data else { return } do{ let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: AnyObject] let results = json["items"] as? [AnyObject] for r in results!{ let item = ApiItem(json: r as! [String: Any]) allItems.append(item) } completion(allItems) } catch let jsonError{ print("JSON error: \(jsonError)") } }.resume() } 方法如下所示:

NSApplication

答案 1 :(得分:-1)

我要做的是使用Singleton,我可以在其中存储数据

class DataManager:NSObject
{
  static let instance  = DataManager()
  override private init(){}


  var items:[ApiItem] = []
}

然后在你的第一种方法中我会这样做:

func getLatest(pageNumber: Int){
    let urlRequest = URL(string: baseUrl + latestUrl + String(pageNumber))

    let requestedData = doRequest(url: urlRequest!, completion: { data -> items in
        // We have the data from doRequest stored in data, but now what?!


      DataManager.instance.items = items
    })

}

这就是我经常处理这种情况的方式。可能有更好的选择......