如何使用Alamofire和Rxswift等待异步api响应?

时间:2017-07-13 06:26:38

标签: ios swift asynchronous alamofire rx-swift

我对async api有疑问 我可以等async api得到答复吗? 在我的情况下,我想要“isAgreen == true”并向用户显示alertcontroller 我不知道怎么做。
感谢。

Class UserModel:NSObject { 

var isAgree:Bool?

func put(_ params:[String:Any], _ callback: @escaping (JSON) -> Void){

let url = self.customUrl(params)
self.requestJSON( .put, url: url, params: params, callback: { json in
  callback(json)
})
}

func getStatus() {

   API.getUserStatus.put(params, { json in

      guard json["status"] != "error" else {

          if json["error"] == "friend agree" {

              self.isAgreen = true

              self.friendship.updateDatabase()
          }
          return
      }
    })
  }
}


class FriendInfoViewController: UIViewController {

func buttonClick(sender:UIButton) {

   let user:UserModel = UserModel()
   user.getStatus()

   if user.isAgreen == true{ //Wait to response and show alertViewController

        let alert = showAlert(title: "Warning", message: "Test", style: .alert)
        self.present(alert, animated: true, completion: nil)
     }
   }
}

2 个答案:

答案 0 :(得分:3)

您可以使用Reactive way(RxSwift)实现您的功能,如下所示。

func getStatus() -> Observable<Bool> {

        return Observable.create({ (observer) -> Disposable in

            API.getUserStatus.put(params, { json in

                guard json["status"] != "error" else {

                    if json["error"] == "friend agree" {

                        observer.onNext(true)
                        self.friendship.updateDatabase()
                    } else {
                        observer.onNext(false)
                    }
                }
               observer.onNext(true)

                //Error event which occurred in your request
                //observer.onError(Error)

                observer.onCompleted()
            })

            return Disposables.create()
        })
    }

你无法得到结果通过以下呼叫:

let user:UserModel = UserModel()
let bag = DisposeBag()

user.getStatus().subscribe(onNext: { (isAgreen) in
            if isAgreen {
                let alert = showAlert(title: "Warning", message: "Test", style: .alert)
                self.present(alert, animated: true, completion: nil)
            }

        }, onError: { (error) in
            //Do stuff when error Event occurred
        }, onCompleted: { 
            //Do stuff when Complete Event occurred
        }).addDisposableTo(bag)
希望能帮到你。

答案 1 :(得分:2)

嘿,你不应该设置一个全局变量。而不是在get Status Method中使用comletionHandler。它可能看起来像:

func getStatus(_ completionHandler: @escaping (Bool) -> Void) {

    API.getUserStatus.put(params, { json in

        guard json["status"] != "error" else {

            if json["error"] == "friend agree" {


                self.friendship.updateDatabase()
                completionHandler(true)
            }
            completionHandler(false)
        }
        completionHandler(true)
    })
}

电话会是:

user.getStatus() { isAgreen in
    if isAgreen {
        // do your stuff if user is logged in
    } else {
        // do your stuff if not logged in
    }
}