How to establish a persistent connection after handling VoIP push from PushKit?

62 Views Asked by At

I am developing a VoIP app using Flutter. I use PushKit to notify iOS client about incoming calls while in terminated state. Handling the VoIP push is happening in AppDelegate.swift. Official Apple docs state that I should establish a connection to your VoIP server in parallel, however I am not sure what is meant by that. In pushRegistry function:

        SwiftFlutterCallkitIncomingPlugin.sharedInstance?.showCallkitIncoming(data, fromPushKit: true)
          
        //Make sure call completion()
        DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
            completion()
        }
        
        DispatchQueue.global(qos: .userInitiated).async {
            self.startMonitoringIncomingCalls()
        }

Then I create a timer:

@objc func checkServerCalls(timer: Timer) {
        let token: UserData? = getUserToken()
        guard token != nil else { return }
        
        let url = URL(string: apiURL + "/calls/user/" + String(token!.user_id) + "/receiver")!
        var request = URLRequest(url: url)
        request.setValue(getBasicAuthHeaders(token: token!.token), forHTTPHeaderField: "Authorization")
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let data = data else { return }
            
            let callsData = try! JSONDecoder().decode(CallList.self, from: data)
     
            
            let firstCall = callsData.calls.first
            
            
            if firstCall?.time_end != nil && firstCall?.time_start == nil {
                DispatchQueue.main.async {
                    SwiftFlutterCallkitIncomingPlugin.sharedInstance?.endAllCalls()
                    UIApplication.shared.endBackgroundTask(self.backgroundTask)
                }
                
                timer.invalidate()
            }
        }
        
        task.resume()
    }
    
    func startMonitoringIncomingCalls() {
        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            self.checkServerCalls(timer: timer)
        }
    }

My app crashes in 2-3 seconds after showing an incoming call notification.

0

There are 0 best solutions below