2016-03-15 70 views
0

这是在AppDelegate中收到推送通知后通知UIViewController的正确方法吗? UIViewController需要在获得推送通知后刷新其内容。 Swift新手如此想确认这是Swift中的一种有效方法。推送通知收到时使用协议更新UIViewController?

的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() { 

    } 
    } 

回答

0

好吧,这一切看起来很好,地道的斯威夫特。有一点需要记住的是,您需要确保从AppDelegate中维护的委托列表中删除视图控制器,当它被解散时。否则,你的视图控制器将不会从内存中移除。您可以在HomeViewController中实现该代码:

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

好的谢谢。但是,如果HomeViewController是一个根控制器,没有必要将它从委托列表中删除吗? – Crashalot

+0

是的,在这种情况下,你不需要。但对于你需要的其他人。 – Shripada