jeudi 9 mars 2017

Swift Data Manager Design Pattern

I am trying to create a data manager to access an API with OAuth 2.0. Before I can get any data, I need to get an OAuth2 token, which I wrote a function for to perform such request. My question pertains to the design pattern of Swift Data Manager classes. Basically I call this function in my DataManager's init() to store the token as a property as displayed below:

class DataManager {

    var OAuth2Token: String = ""

    init() {
        self.getOAuth2Token() { token in
            guard let token = token else { return }
            self.OAuth2Token = token
        }
    }

    func getOAuth2Token(completion: @escaping (_:String?) -> Void) {
        // Fetches credentials
    }

    func getItem(itemID: String, completion: @escaping ([String: Any]?) -> Void) {
        // Uses token to fetch data from the API
    }
}

The above works, but I think it's kind of hacky since we call a self-mutating function in initialization. I was wondering if there is a better, more Swifty design pattern to follow for these kind of things? Should the token be stored as a property of this class?

Aucun commentaire:

Enregistrer un commentaire