0

Many im services automatically display messages once the user on the other end has sent a message.

Right now, the only way I can think of to do this is to use an nstimer which will run the appropriate block of code which fetches the messages and updates the table view. This is resources intensive and can waste one of the requests per second. Is there any way to automate this process and make it happen only when a new message has been sent/received?

2
  • How would I do that? Commented Oct 30, 2015 at 20:46
  • Use func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) in your app delegate. You will be able to inspect the notification payload to determine what the push notification was, and refresh the view accordingly Commented Oct 30, 2015 at 20:55

1 Answer 1

1

Here's an example of using didReceiveRemoteNotification inside of your app delegate to respond to push notifications. In particular, you care about the case where you are receiving the notification while the app is active.

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    if (PFUser.currentUser() == nil) {
        return
    }

    if (application.applicationState == UIApplicationState.Inactive || application.applicationState == UIApplicationState.Background) { 
        // Received the push notification when the app was in the background
        PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)

        // Inspect userInfo for the push notification payload
        if let notificationPayloadTypeKey: String = userInfo["someKey"] as? String {
            // Do something
        }
    } else {
        // Received the push notification while the app is active
        if let notificationPayloadTypeKey: String = userInfo["someKey"] as? String {
            // Use NSNotificationCenter to inform your view to reload
            NSNotificationCenter.defaultCenter().postNotificationName("loadMessages", object: nil)
        }
    }
}

Then you just need to add a listener inside of your view controller. Inside of viewDidLoad add the following which will call the function loadMessages whenever a notification is received.

NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadMessages", name: "loadMessages", object: nil)

If you download the code for Parse's Anypic example project you can see how they handle remote notifications.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.