Reputation: 11
I am trying to gather in an array (for further use) some data that I am getting with consecutive ALAMOFIRE requests. I know there is an asynchronous process, and I believe thats why when I try to printout the dataArray
, it occurs before the Alamofire
requests ended, so it is always empty (attempt 1: please see code). I also try to use dispatch_async on Alamofire
request closure (attempt 2: please see code) and sometimes it prints out the complete array in duplicate and never in the requested order. Could you please help me to find the right way to do it, meaning, gather all collected information according to the requests order and then use the completed dataArray at the right moment?
import UIKit
import Alamofire
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var dataArray = [String]()
for var a = 4; a <= 9; a++ {
request(.GET, "http://api.fixer.io/2015-09-0\(a)?symbols=USD", parameters: nil, encoding: .JSON)
.responseJSON {
(request, response, json, error) -> Void in
let photoInfos = json as! Dictionary<String, NSObject>
let date = photoInfos["date"]! as! String
dataArray.append(date)
println("request: \(request)")
println("response: \(response?.statusCode)")
println("json: \(json)")
println("error: \(error)")
//attempt 2 <begin>
dispatch_async(dispatch_get_main_queue()) {
println(dataArray) // attempt 2
}
//attempt 2 <end>
}
}
//attempt 1 <begin>
println(dataArray)
//attempt 1 <end>
}
}
Upvotes: 1
Views: 148
Reputation: 404
You should use for example SwiftEventBus and separate it from controller class. When response from server comes swiftEventBus will pass an event to MainThread (controller). Just three methods:
Do you still need a response? If yes I extend my response!
Upvotes: 1