在Swift应用中构建Alamofire请求的一种不错的方法

3 swift alamofire

我是iOS noobie,有一个方法可以使用Alamofire从服务器加载一些json并解析JSON。我的代码看起来有点像下面的内容,每5秒重试一次。

func loadData() {
    let end_point = "likes/" + String(UserInfo.sharedData.userId)
    let url = MyConfig.sharedData.url + end_point
    Alamofire.request(.GET, url).responseJSON{ (request, response, json, error) in
        if (error == nil) {
            println(request, response, error)
            var products = ParseProduct(json)
            for product in products {
                self.likes.append(product)
            }
            self.collectionView.reloadData()
        } else {
            println("failed will try again in 5 seconds")
            let delayInSeconds = 5.0
            let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
                dispatch_after(delay, dispatch_get_main_queue()) {
                    self.loadData()
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

对于我的每个Alamofire请求,重复进行此重试似乎很乏味。为多个URL的多个请求构造此代码的好方法是什么。

Rob*_*Rob 5

将重试逻辑移到其自己的方法中。将URL作为参数传递,然后提供completionHandler,调用者将在其中提供自己的自定义逻辑:

func performAndRetryRequestWithURL(url: String, completionHandler:(AnyObject?) -> Void) {
    Alamofire.request(.GET, url).responseJSON{ (request, response, json, error) in
        if error == nil {
            completionHandler(json)
        } else {
            let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC)))
            dispatch_after(delay, dispatch_get_main_queue()) {
                self.performAndRetryRequestWithURL(url, completionHandler: completionHandler)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后loadData可以使用该功能

func loadData() {
    let endPoint = "likes/" + String(UserInfo.sharedData.userId)
    let url = MyConfig.sharedData.url + endPoint
    performAndRetryRequestWithURL(url) { json in
        let products = ParseProduct(json)
        self.likes += products
        self.collectionView.reloadData()
    }
}
Run Code Online (Sandbox Code Playgroud)