如何从 Swift 中的回调语句中获取值



我在我的程序中使用alamofire来调用我并获取数据。它存储在可以从其他类调用的函数中。该函数如下所示:

static func searchSong() {
Alamofire.request(*urlhere*, callback: { response in
parseData(request)
}
}

然后方法parseData遍历返回给我的内容。现在我想发生的是 searchSong(( 实际上能够在我在 parseData 中解析数据时返回数据。我怎样才能在 parseData 结束时获取我所拥有的东西,并将其返回到 searchSong(( 中。

我有打印语句告诉我我已经收到了响应并且 parseData 工作正常,但我不知道如何将我在 parseData 末尾的内容返回给 searchSong,以便 searchSong 可以从调用它的位置返回所需的信息。

让你的 searchSong(( 函数接受回调(要求回调接受 parseData 类型的参数(,然后在 alamofire 请求完成时调用回调并将回调传回 parseData。我相信你已经知道了,但阿拉莫火请求是异步的。处理此类问题的最标准方法是调用回调。

Alamofires 的调用是异步进行的,这意味着您的 searchSong 函数返回值将始终为 Void。 如果要"返回"响应值,请在 searchSong 中添加回调作为参数

func searchSong(returnCallback: (Any) -> Void){
Alamofire.request(*urlhere*, callback: { response in
// Any is the type of your returning element.
returnCallback(/* resposne or wathever you want to return */)
}
}

然后无论你在哪里调用 searchSong,你都会有一个这样的结构:

self.searchSong { (response) in
/* code here */
// here on response you have the request returning value
}

请注意,所有这些过程都是异步的,这是Apple处理HTTP请求的方式,因此Alamofire遵循这一点。

最新更新