菜鸟教程小白 发表于 2022-12-11 19:37:28

ios - 初始化单例异步 iOS


                                            <p><p>我有一个名为 <code>YelpService</code> 的单例。它负责从 Yelp 检索数据。当然,每个 API 调用都必须经过授权。问题是身份验证过程是异步的。如果每次在使用 <code>YelpService</code> 之前都必须检查 yelp 客户端是否被授权,那将是非常多余的。我怎样才能解决这个问题? </p>

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

<p>什么是存储 Yelp 客户端以便进行 API 调用的安全有效的方法?
我知道在 init 中进行网络调用是不好的。 </p>

<pre><code>class YelpService {

    static let _shared = YelpService()

    private let clientId = &#34;id&#34;
    private let clientSecret = &#34;secret&#34;

    var apiClient: YLPClient?

    init() {

      YLPClient.authorize(withAppId: clientId, secret: clientSecret) { (client, error) in
            guard error == nil else {
                print(&#34;YELP AUTH ERROR: \(error!.localizedDescription)&#34;)
                return
            }
            guard let client = client else {
                print(&#34;YELP AUTH ERROR: CLIENT IS NIL&#34;)
                return
            }
            self.apiClient = client
      }
    }
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>你不应该从外部调用 Singleton 类 <code>init()</code>。</p>

<pre><code>class YelpService {

    static let shared = YelpService()

    private let clientId = &#34;id&#34;
    private let clientSecret = &#34;secret&#34;

    var apiClient: YLPClient?

    fileprivate init() {

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

<p>首先,从AppDelegate,检查<code>apiClient</code>是否初始化,如果没有初始化,第一次使用共享对象会自动初始化Singleton类。</p>

<p>在 AppDelegate 中添加通知观察者用于 <code>apiClient</code> 初始化。</p>

<pre><code>if let apiClient = YelpService.shared.apiClient {
   //Do work
}
</code></pre>

<p>或者在通知观察者方法中工作。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 初始化单例异步 iOS,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/48311767/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/48311767/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 初始化单例异步 iOS