异步任务不更改外部变量

异步任务不更改外部变量

我无法从URL保存数据,因为函数处于无限循环中。如何解决?
我的代码:

如果没有“ while”运行,则一切正常。

最佳答案

一种可能的解决方案是将递归函数和调度组(未测试)结合在一起:

func getRegion2(){
    let method = "region/"

    var url = serviceUrl+method
    var myArray: [String] = []

    let group = DispatchGroup()

    func getRegion(with url: String) {
        group.enter()
        Alamofire.request(url).validate().responseJSON { response in
            switch response.result {
            case .success(let data):

                let nextUrl = JSON(data)["next"].stringValue
                myArray = myArray + someArrayFromRespnse
                print(nextUrl)

                if nextUrl != nil {
                    getRegion(with: nextUrl)
                }

                group.leave()
            case .failure(let error):
                print("Request failed with error: \(error)")
            }
        }
    }

    getRegion(with: url)

    group.notify(queue: DispatchQueue.main) {
        print(myArray)
    }
}


我会用一个completionBlock:

func getRegion2(completion: () -> [String]?) {
    let method = "region/"
    var url = serviceUrl+method
    var myArray: [String] = []

    func getRegion(with url: String) {
        Alamofire.request(url).validate().responseJSON { response in
            switch response.result {
            case .success(let data):

                let nextUrl = JSON(data)["next"].stringValue
                myArray = myArray + someArrayFromRespnse
                print(nextUrl)

                if nextUrl != nil {
                    getRegion(with: nextUrl)
                } else {
                    completion(myArray)
                }

            case .failure(let error):
                completion(nil)
            }
        }
    }

    getRegion(with: url)
}

关于ios - 异步任务不更改外部变量。 swift 3,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40260037/

10-14 21:20