JSON 请求的 AlamoFire 异步完成处理程序 [英] AlamoFire asynchronous completionHandler for JSON request

查看:30
本文介绍了JSON 请求的 AlamoFire 异步完成处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 AlamoFire 框架后,我注意到 completionHandler 在主线程上运行.我想知道下面的代码是否是在完成处理程序中创建核心数据导入任务的好习惯:

Having used the AlamoFire framework I've noticed that the completionHandler is run on the main thread. Im wondering if the code below is a good practice for creating a Core Data import task within the completion handler:

Alamofire.request(.GET, "http://myWebSite.com", parameters: parameters)
            .responseJSON(options: .MutableContainers) { (_, _, JSON, error) -> Void in
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in
                    if let err = error{
                        println("Error:(error)")
                        return;
                    }

                    if let jsonArray = JSON as? [NSArray]{                       
                        let importer = CDImporter(incomingArray: jsonArray entity: "Artist", map: artistEntityMap);

                    }
                });
            }

推荐答案

这是一个很好的问题.你的方法是完全有效的.但是,Alamofire 实际上可以帮助您进一步简化此过程.

This is a really good question. Your approach is perfectly valid. However, Alamofire can actually help you streamline this even more.

在示例代码中,您在以下调度队列之间跳转:

In you example code, you are jumping between the following dispatch queues:

  1. NSURLSession 调度队列
  2. 用于验证和序列化程序处理的 TaskDelegate 调度队列
  3. 用于调用完成处理程序的主要调度队列
  4. 用于 JSON 处理的高优先级队列
  5. 用于更新用户界面的主调度队列(如有必要)

如您所见,您正在到处跳来跳去.让我们来看看利用 Alamofire 内部强大功能的替代方法.

As you can see, you're hopping all over the place. Let's take a look at an alternative approach leveraging a powerful feature inside Alamofire.

Alamofire 在其自身的低级处理中内置了一种最佳方法.如果您选择使用它,最终被所有自定义响应序列化程序调用的单个 response 方法支持自定义调度队列.

Alamofire has an optimal approach built into it's own low level processing. The single response method that ultimately gets called by all custom response serializers has support for a custom dispatch queue if you choose to use it.

虽然 GCD 在调度队列之间跳转非常出色,但您希望避免跳转到繁忙的队列(例如主线程).通过消除在异步处理中间跳转回主线程,您可以显着加快速度.以下示例演示了如何使用开箱即用的 Alamofire 逻辑来执行此操作.

While GCD is amazing at hopping between dispatch queues, you want to avoid jumping to a queue that is busy (e.g. the main thread). By eliminating the jump back to the main thread in the middle of the async processing, you can potentially speed things up considerably. The following example demonstrates how to do this using Alamofire logic straight out-of-the-box.

let queue = dispatch_queue_create("com.cnoon.manager-response-queue", DISPATCH_QUEUE_CONCURRENT)

let request = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
request.response(
    queue: queue,
    serializer: Request.JSONResponseSerializer(options: .AllowFragments),
    completionHandler: { _, _, JSON, _ in

        // You are now running on the concurrent `queue` you created earlier.
        println("Parsing JSON on thread: (NSThread.currentThread()) is main thread: (NSThread.isMainThread())")

        // Validate your JSON response and convert into model objects if necessary
        println(JSON)

        // To update anything on the main thread, just jump back on like so.
        dispatch_async(dispatch_get_main_queue()) {
            println("Am I back on the main thread: (NSThread.isMainThread())")
        }
    }
)

Alamofire 3.x(Swift 2.2 和 2.3)

let queue = dispatch_queue_create("com.cnoon.manager-response-queue", DISPATCH_QUEUE_CONCURRENT)

let request = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
request.response(
    queue: queue,
    responseSerializer: Request.JSONResponseSerializer(options: .AllowFragments),
    completionHandler: { response in
        // You are now running on the concurrent `queue` you created earlier.
        print("Parsing JSON on thread: (NSThread.currentThread()) is main thread: (NSThread.isMainThread())")

        // Validate your JSON response and convert into model objects if necessary
        print(response.result.value)

        // To update anything on the main thread, just jump back on like so.
        dispatch_async(dispatch_get_main_queue()) {
            print("Am I back on the main thread: (NSThread.isMainThread())")
        }
    }
)

Alamofire 4.x (Swift 3)

let queue = DispatchQueue(label: "com.cnoon.response-queue", qos: .utility, attributes: [.concurrent])

Alamofire.request("http://httpbin.org/get", parameters: ["foo": "bar"])
    .response(
        queue: queue,
        responseSerializer: DataRequest.jsonResponseSerializer(),
        completionHandler: { response in
            // You are now running on the concurrent `queue` you created earlier.
            print("Parsing JSON on thread: (Thread.current) is main thread: (Thread.isMainThread)")

            // Validate your JSON response and convert into model objects if necessary
            print(response.result.value)

            // To update anything on the main thread, just jump back on like so.
            DispatchQueue.main.async {
                print("Am I back on the main thread: (Thread.isMainThread)")
            }
        }
    )

Alamofire 调度队列分解

以下是与此方法相关的不同调度队列的细分.

Alamofire Dispatch Queue Breakdown

Here is the breakdown of the different dispatch queues involved with this approach.

  1. NSURLSession 调度队列
  2. 用于验证和序列化程序处理的 TaskDelegate 调度队列
  3. 用于 JSON 处理的自定义管理器并发调度队列
  4. 用于更新用户界面的主调度队列(如有必要)

总结

通过消除返回主调度队列的第一跳,您消除了潜在的瓶颈,并使整个请求和处理异步化.太棒了!

Summary

By eliminating the first hop back to the main dispatch queue, you have eliminated a potential bottleneck as well as you have made your entire request and processing asynchronous. Awesome!

话虽如此,我再怎么强调熟悉 Alamofire 真正工作原理的内部结构是多么重要.您永远不知道什么时候会发现真正可以帮助您改进自己的代码的东西.

With that said, I can't stress enough how important it is to get familiar with the internals of how Alamofire really works. You never know when you may find something that can really help you improve your own code.

这篇关于JSON 请求的 AlamoFire 异步完成处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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