vendredi 31 juillet 2015

Singleton Class and multiple asynchronous operations in Swift

I am writing an iOS Swift application that, upon startup, needs to get 2 (or more) sets of data from a server. During initialization, I must do some processing on the sets of data - kind of merging them together. And only then can I start my view controller and interact with the user. The data obtained during initialization is an array of objects that I reuse everywhere in my app.

At first, I put the code in the viewDidLoad of the view controller, but it became messy very quickly. Now, I am putting all this code inside a "singleton" class so that all my view controllers can reuse the same data. My singleton class is defined using the following code excerpt:

class Teams {
  var teams: [Team]
  static var sharedInstance = Teams()

  private init() {
    teams = []
    let queryText = "CardTypeOWSTEXT:Root"
    //The first async call (DataManager invokes the http REST to the server)
    DataManager.spSearch (queryText, success: { teamsJson -> Void in
      let json = JSON(data: teamsJson)
      ...
      // all the code to handle the data received from the server
      ...
    })
    //The second async call
    DataManager.spSocialFollowedSites ({ sitesJson -> Void in
        let json = JSON(data: sitesJson)
       ...
      // all the code to handle the data received from the server
      ...
    })

I am very new to iOS development, and I try to replicate an existing app I wrote in AngularJS. In that app, it is very simple to invoke the REST calls to the server and using promises, all I have to do is wait for both to complete to execute the matching with a statement like:

$q.all([promise1, promise2]).then(...)

but this is javascript/angular, not Swift! I know there are promises libraries (eg. PromiseKit), but I am wondering if this is the right way to do it? Would it be simpler/better with GCD? Also, does my approach using a singleton makes sense? Its purpose is to hold data shared by all the other classes, and in angular, the same concept is a factory and works quite well...

I have read many places and could not get any good guidance, so any help would be appreciated!

Aucun commentaire:

Enregistrer un commentaire