2016-03-15 46 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