OGeek|极客世界-中国程序员成长平台

标题: ios - 初始化单例异步 iOS [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:37
标题: ios - 初始化单例异步 iOS

我有一个名为 YelpService 的单例。它负责从 Yelp 检索数据。当然,每个 API 调用都必须经过授权。问题是身份验证过程是异步的。如果每次在使用 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
        }
    }
}



Best Answer-推荐答案


你不应该从外部调用 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
}

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

关于ios - 初始化单例异步 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48311767/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4