【问题标题】:Initializing Singleton async iOS初始化单例异步 iOS
【发布时间】:2018-06-26 23:07:00
【问题描述】:

我有一个名为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
        }
    }
}

【问题讨论】:

  • 您可以通过在屏幕上显示一些 HUD 或加载程序来阻止用户进行进一步的活动

标签: ios swift asynchronous initialization singleton


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    相关资源
    最近更新 更多