Alamofire无阻塞连接 [英] Alamofire nonblocking connection

查看:73
本文介绍了Alamofire无阻塞连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Alamofire进行基本联网。这是我的问题。我有一个课程

I am using Alamofire for basic networking. Here is my problem. I have a class

class User {
    var name:String?
    var company:String

init () {
  //
   manager = Alamofire.Manager(configuration: configuration)
  }

 func details () {
    //first we login, if login is successful we fetch the result

 manager.customPostWithHeaders(customURL!, data: parameter, headers: header)
          .responseJSON { (req, res, json, error) in
              if(error != nil) {
                  NSLog("Error: \(error)")
            }
             else {
                 NSLog("Success: \(self.customURL)")
                 var json = JSON(json!)
                 println(json)
                     self.fetch()
                      println("I fetched correctly")
                 }
   }

func fetch() {

   manager.customPostWithHeaders(customURL!, data: parameter, headers: header)

            .responseJSON { (req, res, json, error) in
                if(error != nil) {
                    NSLog("Error: \(error)")
                }
                else {
                    NSLog("Success: \(self.customURL)")
                    var json = JSON(json!)
                    println(json)
            //set name and company
      }
   }
}

我的问题是我是否做了

var my user = User()
user.fetch()
println("Username is \(user.name)")

我在控制台上找不到user.name的任何内容。但是,如果我设置了一个断点,则会看到在提取函数中正确获取了用户名和公司。我认为管理器在单独的非阻塞线程中运行,因此不会等待。但是,如果我不知道管理器是否成功完成,我真的不知道如何使用正确的数据初始化班级。那么,如何在Alamofire管理器的所有线程完成工作后正确初始化我的类,以便立即访问?

I don’t get anything on the console for user.name. However if I put a break point, I see that I get username and company correctly inside my fetch function. I think manager runs in separate non blocking thread and doesn’t wait. However I really don’t know how can I initialize my class with correct data if I can’t know whether manager finished successfully. So how can I initialize my class correctly for immediate access after all threads of Alamofire manager did their job?

推荐答案

想在模型对象内部进行联网。相反,您希望在一些更抽象的对象中处理网络层,例如类方法的 Service 。这只是一个简单的示例,但我认为这确实可以使您朝着更好的架构方向发展。

You don't want to do the networking inside your model object. Instead, you want to handle the networking layer in some more abstract object such as a Service of class methods. This is just a simple example, but I think this will really get you heading in a much better architectural direction.

import Alamofire

struct User {
    let name: String
    let companyName: String
}

class UserService {

    typealias UserCompletionHandler = (User?, NSError?) -> Void

    class func getUser(completionHandler: UserCompletionHandler) {
        let loginRequest = Alamofire.request(.GET, "login/url")
        loginRequest.responseJSON { request, response, json, error in
            if let error = error {
                completionHandler(nil, error)
            } else {
                println("Login Succeeded!")

                let userRequest = Alamofire.request(.GET, "user/url")
                userRequest.responseJSON { request, response, json, error in
                    if let error = error {
                        completionHandler(nil, error)
                    } else {
                        let jsonDictionary = json as [String: AnyObject]
                        let user = User(
                            name: jsonDictionary["name"]! as String,
                            companyName: jsonDictionary["companyName"]! as String
                        )

                        completionHandler(user, nil)
                    }
                }
            }
        }
    }
}

UserService.getUser { user, error in
    if let user = user {
        // do something awesome with my new user
        println(user)
    } else {
        // figure out how to handle the error
        println(error)
    }
}

由于登录和用户请求都是异步的,因此只有两个请求都完成并且您具有有效的User对象后,您才能开始使用User对象。闭包是捕获异步任务完成后要运行的逻辑的好方法。以下是Alamofire和异步网络上的其他几个线程,它们也可能会对您有所帮助。

Since both the login and user requests are asynchronous, you cannot start using the User object until both requests are completed and you have a valid User object. Closures are a great way to capture logic to run after the completion of asynchronous tasks. Here are a couple other threads on Alamofire and async networking that may also help you out.

  • Handling Multiple Network Calls
  • Returning a Value with Alamofire

希望这能给我们一些启示。

Hopefully this sheds some light.

这篇关于Alamofire无阻塞连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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