简体   繁体   中英

Can I call static method from background queue in swift?

I have a static getData() method in the ServerCommunication class can I call this method from background queue.

//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: "")
     }
}

Can anybody explain what will the impact on thread executions Or may I need to define ServerCommunication class as Singleton?

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

#Edit1 Some more explanations

This problem occurred when I am trying to open a specific viewController when Push notification occurs. I am using a third party library called FAPanelController which accept a center, left and right viewController respectively.

Code sample:

@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()
        })
}
}

You can use Closures for that

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)
    })
}

There are several reasons of any impact I could imagine:
1. At some point your getData modifies UI, which I believe isn't case here.
2. getData modifies any variables outside. Thus you need to wrap these modifications in synchronous queue.
3. getData calls other mutating methods. The solution is same as in 2 .
Otherwise it's safe to call your static method from anywhere. The Singleton approach is not necessary, unless you need additional setup for your calls.

是的,您可以在后台线程中调用静态方法。

ClassName.performSelector(inBackground: #selector(self.ClassMethod), with: nil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM