1 回答

TA貢獻1798條經(jīng)驗 獲得超3個贊
處理這個的一種方法是將一個閉包(我通常稱之為a completionHandler
)傳遞給你的siteInfo
函數(shù)并調(diào)用它的內(nèi)部Alamofire.request
閉包:
func siteInfo(completionHandler: (String?, NSError?) -> ()) -> () { Alamofire.request(.GET, MY_API_END_POINT).responseJSON { (request, response, JSON, error) in let info = JSON as? NSDictionary // info will be nil if it's not an NSDictionary let str = info?["access_key"] as? String // str will be nil if info is nil or the value for "access_key" is not a String completionHandler(str, error) }}
然后像這樣調(diào)用它(不要忘記錯誤處理):
siteInfo { (str, error) in if str != nil { // Use str value } else { // Handle error / nil value }}
在評論中你問:
那么如果你只能在閉包內(nèi)部做東西而不影響閉包之外的對象,你將如何保存從get請求中收集的信息?另外,如何跟蹤知道請求何時完成?
您可以從閉包內(nèi)部將get請求的結(jié)果保存到類中的實例變量中; 封閉阻止你做這件事沒有任何關系。你從那里做什么真的取決于你想用這些數(shù)據(jù)做什么。
一個例子怎么樣?
由于看起來您正在獲取獲取請求的訪問密鑰表單,因此您可能需要將其用于將來在其他功能中發(fā)出的請求。
在這種情況下,你可以這樣做:
注意:異步編程是一個很大的主題; 太多了,無法覆蓋這里。這只是您如何處理從異步請求中獲取的數(shù)據(jù)的一個示例。
public class Site { private var _accessKey: String? private func getAccessKey(completionHandler: (String?, NSError?) -> ()) -> () { // If we already have an access key, call the completion handler with it immediately if let accessKey = self._accessKey { completionHandler(accessKey, nil) } else { // Otherwise request one Alamofire.request(.GET, MY_API_END_POINT).responseJSON { (request, response, JSON, error) in let info = JSON as? NSDictionary // info will be nil if it's not an NSDictionary let accessKey = info?["access_key"] as? String // accessKey will be nil if info is nil or the value for "access_key" is not a String self._accessKey = accessKey completionHandler(accessKey, error) } } } public func somethingNeedingAccessKey() { getAccessKey { (accessKey, error) in if accessKey != nil { // Use accessKey however you'd like here println(accessKey) } else { // Handle error / nil accessKey here } } }}
使用該設置,somethingNeedingAccessKey()
第一次調(diào)用將觸發(fā)獲取訪問密鑰的請求。之后的任何調(diào)用somethingNeedingAccessKey()
都將使用已存儲的值self._accessKey
。如果你somethingNeedingAccessKey
在傳遞給閉包的其余部分工作getAccessKey
,你可以確定你的accessKey
總是有效的。如果您需要另一個需要的功能accessKey
,只需按照相同的方式somethingNeedingAccessKey
編寫即可。
public func somethingElse() { getAccessKey { (accessKey, error) in if accessKey != nil { // Do something else with accessKey } else { // Handle nil accessKey / error here } }}
- 1 回答
- 0 關注
- 567 瀏覽
添加回答
舉報