初始化Singleton异步iOS

时间:2018-01-17 23:41:30

标签: ios swift asynchronous initialization singleton

我有一个名为YelpService的单身人士。它负责从Yelp中检索数据。当然,每个API调用都必须经过授权。问题是auth进程是异步的。如果我必须在每次使用YelpService之前检查yelp客户端是否被授权,那将是非常多余的。我怎么能绕过这个?

另外,如果我在带有完成处理程序的方法中添加身份验证逻辑并嵌套在实际进行API调用的其他方法中,我会收到错误:Command failed due to signal: Segmentation fault: 11

什么是安全有效的存储Yelp客户端的方式,以便我可以进行API调用? 我知道在init中进行网络调用很糟糕。

class YelpService {

    static let _shared = YelpService()

    private let clientId = "id"
    private let clientSecret = "secret"

    var apiClient: YLPClient?

    init() {

        YLPClient.authorize(withAppId: clientId, secret: clientSecret) { (client, error) in
            guard error == nil else {
                print("YELP AUTH ERROR: \(error!.localizedDescription)")
                return
            }
            guard let client = client else {
                print("YELP AUTH ERROR: CLIENT IS NIL")
                return
            }
            self.apiClient = client
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你不应该从外面调用Singleton类init()

class YelpService {

    static let shared = YelpService()

    private let clientId = "id"
    private let clientSecret = "secret"

    var apiClient: YLPClient?

    fileprivate init() {

        YLPClient.authorize(withAppId: clientId, secret: clientSecret) { (client, error) in
            guard error == nil else {
                print("YELP AUTH ERROR: \(error!.localizedDescription)")
                return
            }
            guard let client = client else {
                print("YELP AUTH ERROR: CLIENT IS NIL")
                return
            }
            self.apiClient = client
            // Here, post notification
        }
    }
}

首先,从AppDelegate开始,检查apiClient是否已初始化,因此如果未初始化,则首次使用共享对象将自动启动Singleton类。

在AppDelegate中添加通知观察器以进行apiClient初始化。

if let apiClient = YelpService.shared.apiClient {
   //Do work
}

或在通知观察员方法中工作。