ios - 我可以快速从后台队列调用静态方法吗?

标签 ios swift multithreading background

我在 ServerCommunication 类中有一个静态的 getData() 方法,我可以从后台队列调用这个方法吗?

//ServerCommunication.swift

import UIKit
import Foundation


class ServerCommunication
{
      class func getData(url: String, sessionId: String) -> ServerResponse {
            //server communication code goes here
      }
}

func populateData() {
     DispatchQueue.global(qos: .background).async {
           let response = ServerCommunication.getData(url: URL, sessionId: "")
     }
}

任何人都可以解释对线程执行的影响吗?或者我可能需要将 ServerCommunication 类定义为 Singleton?

getData() static class executed multiple times when calling from background queue

#Edit1 更多解释

发生推送通知时,当我尝试打开特定的 viewController 时,会出现此问题。我正在使用名为 FAPanelController 的第三方库分别接受中心、左和右 viewController。

代码示例:

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//Now I want to open a viewController
if let panel = self.window?.rootViewController as? FAPanelController     
{
    let centerNavVC = storyboard.instantiateViewController(withIdentifier: "HomeViewController") as! UINavigationController
        let vc = centerNavVC.topViewController as! HomeViewController
        panel.center(centerNavVC, afterThat: {
            //HomeViewController has a method populateData() in viewWillAppear()
        })
}
}

最佳答案

你可以为此使用闭包

class ServerCommunication
{
    class func getData(url: String, sessionId: String, success: @escaping ((_ responseObject: ServerResponse?) -> Void)) {
        //server communication code goes here
        success(serverData) // serverData is a server response
    }
}

func populateData() {
    ServerCommunication.getData(url: "", sessionId: "", success: { (response) in
       // You can handle response here
       print(response)
    })
}

关于ios - 我可以快速从后台队列调用静态方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50410470/

相关文章:

ios - 在 iOS 错误中解析 JSON 图像 url

iOS Rich Push notifications with Xcode, Swift3 但无法获取图像

ios - '传递给不带参数的调用的参数'实例化 HKWorkoutRouteQuery

swift - 具有可选值的自定义运算符

mysql - 重启多线程perl脚本并关闭mysql连接

ios - iCarousel - 动态更改中心项目 iOS

ios - 使用 Swift 在 iOS 聊天应用程序中查看表情符号

ios - Realm 对象服务器创建数据库和 ROS 但不同步

windows - 拥有多个线程池与单个线程池相比有什么好处?

java - 以异步方式实现长轮询