【问题标题】:Receive Push Messages in iOS在 iOS 中接收推送消息
【发布时间】:2015-01-07 09:52:55
【问题描述】:
要在 iOS 中接收推送消息,我使用以下方法:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
这个方法在我的 AppDelegate.m 中。一切正常。我的问题是这个方法是否有可能不在 AppDelegate 中而是在其他任何地方?!
【问题讨论】:
标签:
ios
objective-c
iphone
ios8
push-notification
【解决方案1】:
不,这是不可能的,因为这是由 iOS 决定的。查看文档here。
您可以做的是创建一个专用类(例如PushNotificationHandler),该类应该用于处理您的推送通知并在application:didReceiveRemoteNotification:fetchCompletionHandler: 中调用它。
【解决方案2】:
使用 NSNotificationCenter,您可以轻松地广播您的推送通知:
广播:
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
NSDictionary *userInfo = @{@"localNotification": notification};
[[NSNotificationCenter defaultCenter] postNotificationName:@"DOMyApplicationDidReceiveLocalNotification"
object:notification
userInfo:userInfo];
}
在需要的地方听:
[[NSNotificationCenter defaultCenter] addObserverForName:@"DOMyApplicationDidReceiveLocalNotification"
object:nil
queue:nil
usingBlock:^(NSNotification *note)
{
UILocalNotification *localNotification = note.userInfo[@"localNotification"];
//...
}];
NSNotificationCenter 提供了多种监听方法,不仅仅是这里展示的基于块的。