swift - 轮询 url 直到响应为某个值

标签 swift promise alamofire promisekit

我刚刚开始使用 Swift(一种非常好的语言)编码,我正在尝试制作一个需要用户使用第三方登录服务登录的应用。

身份验证流程的基础如下所示: 1. 用户输入 ssn(瑞典人编号)并回车。
2. POST 到返回 json blob 的 url:

{
    "transactionId": "a transaction id",
    "expires": "date sting in some iso format",
    "autostartToken": "irrelevant for my usage"
}

3。轮询一个使用第 2 步中的 transactionId 的 url。
此 url 返回一个 json blob:

{
    "state": "OUTSTANDING_TRANSACTION",
    // other stuff that's uninteresting
}

一旦用户使用移动身份验证应用授予访问权限,此 url 将返回一个更复杂的 json blob。 state 将变为“COMPLETED”。 4. 从可从步骤 3 中的 blob 获得的最终 url 接收身份验证 token (一旦状态为“已完成”)。
5. ???
6. 利润!

所以我的“问题”是我无法真正弄清楚(以我有限的快速知识)如何执行第 3 步。轮询 url 直到状态为“已完成”(或第 2 步的过期已通过,它应该会失败)。

我在 javascript 中做了一次 hacky 尝试来试用该服务,它看起来像这样:

this.postMethodThatReturnsAPromise(url, data).then(response => {
    let {transactionId} = response.body;
        let self = this,
            max = 10,
            num = 0;
        return new Promise(function (resolve, reject) {
            (function poll() {
                self._get(`baseurl/${transactionId}`).then(res => {
                    let {state} = res.body;
                    if (state !== 'COMPLETE' && num < max) {
                        setTimeout(poll, 2000);
                    } else if (state === 'COMPLETE') {
                        return resolve(res);
                    }
                });
                num++;
            })();
        });
    })

我如何在 swift 3 中使用 Alamofire 和 Promisekit 执行此操作?

return Alamofire.request(url, method: .post, /* rest is omitted */).responseJSON().then { response -> String in
    let d = res as! Dictionary<String, Any>
    return d["transactionId"]
}.then { transactionId -> [String: Any] in
    // TODO: The polling until blob contains "state" with value "COMPLETED"
    // Return the final json blob as dict to the next promise handler
}.then { data in
}

最佳答案

这是这个想法的一个很好的通用版本:

发件人:https://gist.github.com/dtartaglia/2b19e59beaf480535596

/**
Repeadetly evaluates a promise producer until a value satisfies the predicate.
`promiseWhile` produces a promise with the supplied `producer` and then waits
for it to resolve. If the resolved value satifies the predicate then the
returned promise will fulfill. Otherwise, it will produce a new promise. The
method continues to do this until the predicate is satisfied or an error occurs.
- Returns: A promise that is guaranteed to fulfill with a value that satisfies
the predicate, or reject.
*/

func promiseWhile<T>(pred: (T) -> Bool, body: () -> Promise<T>, fail: (() -> Promise<Void>)? = nil) -> Promise<T> {
    return Promise { fulfill, reject in
        func loop() {
            body().then { (t) -> Void in
                if !pred(t) { fulfill(t) }
                else {
                    if let fail = fail {
                        fail().then { loop() }
                        .error { reject($0) }
                    }
                    else { loop() }
                }
            }
            .error { reject($0) }
        }
        loop()
    }
}

关于swift - 轮询 url 直到响应为某个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44607090/

相关文章:

javascript - 循环中的 Ajax 调用等到全部完成(错误或成功)

javascript - Node.js promise 和异步异常

swift - viewForAnnotation 未被调用(使用 Alamofire 解析 JSON)

ios - 如何在 swifty_viper 实现中使用 ModuleConfiguration 和 ModuleInitializer

ios - 当用户点击 UITextfield 时以编程方式实现 UIPickerView

ios - Swift Parse.com UITableView 在更新 NSMutableArray 后不会重新加载数据

swift - Alamofire https 请求仅在 NSExceptionAllowsInsecureHTTPLoads 设置为 true 时有效

ios - XCode/Swift 无法更改文本标签位置

scala - 理解 Scala 的 Futures 和 Promises

ios - 如何公开我的 Struct 变量?