检查从Alamofire和斯威夫特多个异步响应 [英] Checking for multiple asynchronous responses from Alamofire and Swift

查看:134
本文介绍了检查从Alamofire和斯威夫特多个异步响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写这取决于从各种网站/服务数据的应用程序,并且涉及基于来自这些不同源的数据执行计算,以产生最终产品。

I am writing an application that depends on data from various sites/service, and involves performing calculations based on data from these different sources to produce an end product.

我写的示例类有两个功能下,从两个来源收集数据。我选择做不同的功能,因为有时候我们应用根据来源不同的认证方法,但在这个例子中,我刚刚剥离下来,最简单的形式。这两个功能使用Alamofire火起飞和处理请求。

I have written an example class with two functions below that gathers data from the two sources. I have chosen to make the functions different, because sometimes we apply different authentication methods depending on the source, but in this example I have just stripped them down to their simplest form. Both of the functions use Alamofire to fire off and handle the requests.

然后我有一个初始化函数,它说,如果我们已经成功收集的数据来自两个来源,然后加载另一个榫文件,否则最多等待几秒钟,如果没有响应已经返回,然后加载服务器错误笔尖文件。

I then have an initialisation function, which says if we have successfully gathered data from both sources, then load another nib file, otherwise wait up to for seconds, if no response has been returned, then load a server error nib file.

我试图使这个例子尽可能简单。本质。这是一种逻辑的,我想跟进。不幸的是,这似乎目前并不在其目前的实施工作。

I've tried to make this example as simple as possible. Essentially. This is the kind of logic I would like to follow. Unfortunately it appears this does not currently work in its current implementation.

import Foundation

class GrabData{
    var data_source_1:String?
    var data_source_2:String?

    init(){    
        // get data from source 1
        get_data_1{ data_source_1 in
            println("\(data_source_1)")
        }

        // get data from source 2
        get_data_2{ data_source_1 in
            println("\(data_source_1)")
        }

        var timer = 0;
        while(timer<5){
            if((data_source_1 == nil) && (data_source_2 == nil)){
                // do nothing unless 4 seconds has elapsed
                if (timer == 4){
                    // load server error nib
                }
            }else{
                // load another nib, and start manipulating data
            }
            // sleep for 1 second
            sleep(1)
            timer = timer+1
        }    
    }

    func get_data_1(completionHandler: (String) -> ()) -> () {
        if let datasource1 = self.data_source_1{
            completionHandler(datasource1)
        }else{
            var url = "http://somewebsite.com"
            Manager.sharedInstance.request(.GET, url).responseString {
                (request, response, returnedstring, error) in
                println("getting data from source 1")
                let datasource1 = returnedstring
                self.data_source_1 = datasource1
                completionHandler(datasource1!)
            }
        }
    }

    func get_data_2(completionHandler: (String) -> ()) -> () {    
        if let datasource2 = self.data_source_2{
            completionHandler(datasource2)
        }else{
            var url = "http://anotherwebsite.com"
            Manager.sharedInstance.request(.GET, url).responseString {
                (request, response, returnedstring, error) in
                println("getting data from source 2")
                let datasource2 = returnedstring
                self.data_source_2 = datasource2
                completionHandler(datasource2!)
            }
        }
    }
}

我知道,我可以把内第一,第二封init函数里面,不过,我不认为这将是最好的做法,我实际上是从超过2来源拉动,所以关闭为N关闭深。

I know that i could put the second closure within the first inside the init function, however, I don't think this would be best practice and I am actually pulling from more than 2 sources, so the closure would be n closures deep.

要搞清楚,以检查是否多个数据源给予了有效响应的最佳方式任何帮助,并处理了适当的将是更AP preciated。

Any help to figuring out the best way to checking if multiple data sources gave a valid response, and handling that appropriately would be much appreciated.

推荐答案

比循环过程更好,这将阻止线程,你可以使用调度组来跟踪,当被要求做的。所以发出的每个请求的前进入组,离开组时的要求做,并成立了通知块/关闭时,所有的工作组任务完成后,将调用:

Better than that looping process, which would block the thread, you could use dispatch group to keep track of when the requests were done. So "enter" the group before issuing each of the requests, "leave" the group when the request is done, and set up a "notify" block/closure that will be called when all of the group's tasks are done:

let group = dispatch_group_create()

dispatch_group_enter(group)
retrieveDataFromURL(url1, parameters: firstParameters) {
    dispatch_group_leave(group)
}

dispatch_group_enter(group)
retrieveDataFromURL(url2, parameters: secondParameters) {
    dispatch_group_leave(group)
}

dispatch_group_notify(group, dispatch_get_main_queue()) {
    println("both requests done")
}

另一种方法是把它们包装请求的异步内的NSOperation 子(让他们取消,让您对限制并发度等控制),但是这更复杂的,所以你可能需要如上图所示,开始和讯集团。

The other approach is to wrap these requests within an asynchronous NSOperation subclass (making them cancelable, giving you control over constraining the degree of concurrency, etc.), but that's more complicated, so you might want to start with dispatch groups as shown above.

这篇关于检查从Alamofire和斯威夫特多个异步响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆