UILocalNotification 在 iOS 10 中已弃用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37938771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UILocalNotification is deprecated in iOS 10
提问by Roohul
It may be a question in advance but I wonder what to use instead of UILocalNotification
in iOS 10. I am working on an app which has deployment target iOS 8 so will it be ok to use UILocalNotification
?
这可能是一个提前的问题,但我想知道UILocalNotification
在 iOS 10 中使用什么来代替。我正在开发一个部署目标为 iOS 8 的应用程序,所以可以使用UILocalNotification
吗?
回答by ElonChan
Yes, you can use UILocalNotification
, old APIs also works fine with iOS 10, but we had better use the APIs in the User Notifications framework instead. There are also some new features, you can only use with iOS 10 User Notifications framework.
是的,您可以使用UILocalNotification
,旧的 API 也适用于 iOS 10,但我们最好使用用户通知框架中的 API。还有一些新功能,您只能与 iOS 10 用户通知框架一起使用。
This also happens to Remote Notification, for more information: Here.
这也发生在远程通知中,有关更多信息:这里。
New Features:
新功能:
- Now you can either present alert, sound or increase badge while the app is in foreground too with iOS 10
- Now you can handle all event in one place when user tapped (or slided) the action button, even while the app has already been killed.
- Support 3D touch instead of sliding gesture.
- Now you can remove specific local notifications with just one line of code.
- Support Rich Notification with custom UI.
- 现在,您可以在应用程序处于前台时使用 iOS 10 显示警报、声音或增加徽章
- 现在,当用户点击(或滑动)操作按钮时,您可以在一个地方处理所有事件,即使应用程序已经被杀死。
- 支持 3D 触摸代替滑动手势。
- 现在,您只需一行代码即可删除特定的本地通知。
- 支持带有自定义 UI 的丰富通知。
It is really easy for us to convert UILocalNotification
APIs to iOS 10
User Notifications framework APIs, they are really similar.
我们很容易将UILocalNotification
API转换为 iOS 10 用户通知框架 API,它们非常相似。
I wrote a demo here to show how to use new and old APIs at the same time: iOS 10 Adaptation Tips.
我在这里写了一个演示来展示如何同时使用新旧 API: iOS 10 适配技巧。
For example,
例如,
With Swift implementation:
使用 Swift 实现:
import UserNotifications
/// Notification become independent from UIKit import UserNotifications
request authorization for localNotification
let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. }
schedule localNotification
update application icon badge number
@IBAction func triggerNotification(){ let content = UNMutableNotificationContent() content.title = NSString.localizedUserNotificationString(forKey: "Elon said:", arguments: nil) content.body = NSString.localizedUserNotificationString(forKey: "Hello Tom!Get up, let's play with Jerry!", arguments: nil) content.sound = UNNotificationSound.default() content.badge = UIApplication.shared().applicationIconBadgeNumber + 1; content.categoryIdentifier = "com.elonchan.localNotification" // Deliver the notification in 60 seconds. let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60.0, repeats: true) let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger) // Schedule the notification. let center = UNUserNotificationCenter.current() center.add(request) } @IBAction func stopNotification(_ sender: AnyObject) { let center = UNUserNotificationCenter.current() center.removeAllPendingNotificationRequests() // or you can remove specifical notification: // center.removePendingNotificationRequests(withIdentifiers: ["FiveSecond"]) }
导入用户通知
/// Notification become independent from UIKit import UserNotifications
为 localNotification 请求授权
let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. }
安排本地通知
更新应用程序图标徽章编号
@IBAction func triggerNotification(){ let content = UNMutableNotificationContent() content.title = NSString.localizedUserNotificationString(forKey: "Elon said:", arguments: nil) content.body = NSString.localizedUserNotificationString(forKey: "Hello Tom!Get up, let's play with Jerry!", arguments: nil) content.sound = UNNotificationSound.default() content.badge = UIApplication.shared().applicationIconBadgeNumber + 1; content.categoryIdentifier = "com.elonchan.localNotification" // Deliver the notification in 60 seconds. let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60.0, repeats: true) let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger) // Schedule the notification. let center = UNUserNotificationCenter.current() center.add(request) } @IBAction func stopNotification(_ sender: AnyObject) { let center = UNUserNotificationCenter.current() center.removeAllPendingNotificationRequests() // or you can remove specifical notification: // center.removePendingNotificationRequests(withIdentifiers: ["FiveSecond"]) }
Objective-C implementation:
Objective-C 实现:
import UserNotifications
// Notifications are independent from UIKit #import <UserNotifications/UserNotifications.h>
request authorization for localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!error) { NSLog(@"request authorization succeeded!"); [self showAlert]; } }];
schedule localNotification
update application icon badge number
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; content.title = [NSString localizedUserNotificationStringForKey:@"Elon said:" arguments:nil]; content.body = [NSString localizedUserNotificationStringForKey:@"Hello Tom!Get up, let's play with Jerry!" arguments:nil]; content.sound = [UNNotificationSound defaultSound]; // 4. update application icon badge number content.badge = [NSNumber numberWithInteger:([UIApplication sharedApplication].applicationIconBadgeNumber + 1)]; // Deliver the notification in five seconds. UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5.f repeats:NO]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond" content:content trigger:trigger]; /// 3. schedule localNotification UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@"add NotificationRequest succeeded!"); } }];
导入用户通知
// Notifications are independent from UIKit #import <UserNotifications/UserNotifications.h>
为 localNotification 请求授权
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!error) { NSLog(@"request authorization succeeded!"); [self showAlert]; } }];
安排本地通知
更新应用程序图标徽章编号
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; content.title = [NSString localizedUserNotificationStringForKey:@"Elon said:" arguments:nil]; content.body = [NSString localizedUserNotificationStringForKey:@"Hello Tom!Get up, let's play with Jerry!" arguments:nil]; content.sound = [UNNotificationSound defaultSound]; // 4. update application icon badge number content.badge = [NSNumber numberWithInteger:([UIApplication sharedApplication].applicationIconBadgeNumber + 1)]; // Deliver the notification in five seconds. UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5.f repeats:NO]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond" content:content trigger:trigger]; /// 3. schedule localNotification UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@"add NotificationRequest succeeded!"); } }];
updated
更新
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'time interval must be at least 60 if repeating'
由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“如果重复,时间间隔必须至少为 60”
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60, repeats: true)
回答by Golan Shay
Apple have done it again, the correct implementation is: AppDelegate.swift
苹果又做了一遍,正确的实现是:AppDelegate.swift
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.currentNotificationCenter()
center.requestAuthorizationWithOptions([.Alert, .Sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
} else {
// Fallback on earlier versions
}
and don't forget to add
并且不要忘记添加
import UserNotifications
回答by James Rochabrun
Local Notifications for iOS 10 in Objective-C.
Objective-C 中 iOS 10 的本地通知。
If you have been programming for a while I am sure you are familiar with the UILocalNotification
class, and right now with the arrival of iOS 10 you can see that UILocalNotification
has been deprecated. For a detailed implementation visit this blog post.
如果您已经编程了一段时间,我相信您对这个UILocalNotification
类很熟悉,现在随着 iOS 10 的到来,您可以看到它UILocalNotification
已被弃用。有关详细实现,请访问此博客文章。
回答by Faris
swift 4
迅捷 4
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
} else {
// REGISTER FOR PUSH NOTIFICATIONS
let notifTypes:UIUserNotificationType = [.alert, .badge, .sound]
let settings = UIUserNotificationSettings(types: notifTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
application.applicationIconBadgeNumber = 0
}
MARK: - DELEGATES FOR PUSH NOTIFICATIONS
马克: - 推送通知的代表
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let installation = PFInstallation.current()
installation?.setDeviceTokenFrom(deviceToken)
installation?.saveInBackground(block: { (succ, error) in
if error == nil {
print("DEVICE TOKEN REGISTERED!")
} else {
print("\(error!.localizedDescription)")
}
})
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
print("\(userInfo)")
// PFPush.handle(userInfo)
if application.applicationState == .inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(inBackground: userInfo, block: nil)
}
}