异步任务不会更改外部变量。斯威夫特3

时间:2016-10-26 10:38:55

标签: ios swift swift3 alamofire

我无法保存来自网址的数据,因为无限循环中的功能。如何解决? 我的代码:

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

    var url = serviceUrl+method
    var myArray: [String]()
    while(url != nil){

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

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

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

如果在没有" while"的情况下运行,那么一切正常。

1 个答案:

答案 0 :(得分:0)

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

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)
}