Search code examples
iosswiftpush-notificationvoippushkit

Show an alert even when the app is not running


enter image description hereI am doing an app in which I want the user to be notified of something even when the app is not running. Just like in the uber driver app the user is alerted to accept/Reject a ride request. Is this possible with VoIP and PushKit? Which is the best way doing it ?


Solution

  • Yes, this is possible with pushkit silent notification.

    Once you receive push kit payload you have to schedule local notification.

    You can make local notification interactive with accept / Reject ride request and do appropriate thing on tap event like API calling, SQLite etc.

    Refer below code. I have drafted this as per VOIP calling feature, you can draft as per your requirement.

    func pushRegistry(registry: PKPushRegistry!, didReceiveIncomingPushWithPayload payload: PKPushPayload!, forType type: String!) {
            // Process the received push
    
            var arrTemp = [NSObject : AnyObject]()
            arrTemp = payload.dictionaryPayload
    
            let dict : Dictionary <String, AnyObject> = arrTemp["aps"] as! Dictionary<String, AnyObject>
    
    
            if "IfUserHasLoggedInWithApp" // Check this flag then only proceed
            {                
    
                if UIApplication.sharedApplication().applicationState == UIApplicationState.Background || UIApplication.sharedApplication().applicationState == UIApplicationState.Inactive
                {
    
                    if "CheckForIncomingCall" // Check this flag to know incoming call or something else
                    {
    
                        var strTitle : String = dict["alertTitle"] as? String ?? ""
                        let strBody : String = dict["alertBody"] as? String ?? ""
                        strTitle = strTitle + "\n" + strBody
    
                        let notificationIncomingCall = UILocalNotification()
    
                        notificationIncomingCall.fireDate = NSDate(timeIntervalSinceNow: 1)
                        notificationIncomingCall.alertBody =  strTitle
                        notificationIncomingCall.alertAction = "Open"
                        notificationIncomingCall.soundName = "SoundFile.mp3"
                        notificationIncomingCall.category = dict["category"] as? String ?? ""
    
                        notificationIncomingCall.userInfo = "As per payload you receive"
    
                        UIApplication.sharedApplication().scheduleLocalNotification(notificationIncomingCall)
    
                        }
                        else
                        {
                            //  something else
                        }
    
            }
        }
    
    }
    

    Refer more things about pushkit integration and payload.

    https://github.com/hasyapanchasara/PushKit_SilentPushNotification

    enter image description here