收到推送通知时使用协议更新UIViewController?

时间:2016-03-15 02:58:09

标签: ios swift uiviewcontroller push-notification appdelegate

这是在AppDelegate中收到推送通知后通知UIViewController的正确方法吗?获取推送通知后,UIViewController需要刷新其内容。 Swift的新手,所以想确认这是Swift中的一种有效方法。

的AppDelegate:

protocol PushNotificationDelegate : class {
    func didReceivePushNotification()
}


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    var pushDelegates = [PushNotificationDelegate]()

    ...

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
        PFPush.handlePush(userInfo)
        if application.applicationState == UIApplicationState.Inactive {
            PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
        }

        // Notify delegates
        for delegate in pushDelegates {
            delegate.didReceivePushNotification()
        }
    }


    func addPushNotificationDelegate(newDelegate: PushNotificationDelegate) {
        if (pushDelegates.indexOf{$0 === newDelegate} == nil) {
            pushDelegates.append(newDelegate)
        }
    }
}

的UIViewController:

class HomeViewController: UIViewController, PushNotificationDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        ...

        // Get notified when push notifications come in
        if let delegate = UIApplication.sharedApplication().delegate as? AppDelegate {
            delegate.addPushNotificationDelegate(self)
        }
    }


   func didReceivePushNotification() {

   }
   }

1 个答案:

答案 0 :(得分:0)

嗯,这一切看起来都很好,也很惯用Swift。要记住的一件事是,您需要确保从AppDelegate中维护的委托列表中删除视图控制器,当它被解除时。否则,您的视图控制器将不会从内存中删除。您可以在HomeViewController中实现该代码:

-(void)viewWillDisappear(animated:Bool){
   [super viewWillDisappear]
//Remove 'self' from the delegate array maintained in AppDelegate.
}