ios - Async task don't change external variable. Swift 3 -
i can't save data url, because function in infinit loop. how fix it? code:
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 error: \(error)") } } } print(myarray) }
if run without "while", works fine.
one possible solution combine recursive function , dispatch group (not tested):
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 error: \(error)") } } } getregion(with: url) group.notify(queue: dispatchqueue.main) { print(myarray) } }
i use 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) }
Comments
Post a Comment