我在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() }) } }
解决方法
您可以使用Closures
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) }) }