gpt4 book ai didi

ios - 收到推送通知时使用协议(protocol)更新 UIViewController?

转载 作者:行者123 更新时间:2023-11-30 13:36:33 25 4
gpt4 key购买 nike

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

应用程序委托(delegate):

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

}
}

最佳答案

嗯,这一切看起来都很好,而且很符合 Swift 的习惯。需要记住的一件事是,当 View Controller 被解除时,您需要确保从 AppDelegate 中维护的委托(delegate)列表中删除 View Controller 。否则,您的 View Controller 将不会从内存中删除。您可以在 HomeViewController 中实现该代码:

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

关于ios - 收到推送通知时使用协议(protocol)更新 UIViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com