Answers:
这是适用于我的项目的LocalNotification的示例代码。
目标C:
AppDelegate
文件中的此代码块:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
// Override point for customization after application launch.
return YES;
}
// This code block is invoked when application is in foreground (active-mode)
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
UIAlertView *notificationAlert = [[UIAlertView alloc] initWithTitle:@"Notification" message:@"This local notification"
delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[notificationAlert show];
// NSLog(@"didReceiveLocalNotification");
}
.m文件中的以下代码块ViewController
:
-(IBAction)startLocalNotification { // Bind this method to UIButton action
NSLog(@"startLocalNotification");
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7];
notification.alertBody = @"This is local notification!";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = 10;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
上面的代码在按绑定的按钮时,在7秒的时间间隔后显示一个AlertView,startLocalNotification
如果应用程序在后台,则显示BadgeNumber
为10,并带有默认通知声音。
这段代码在iOS 7.x和更低版本上工作正常,但在iOS 8上,它将在控制台上提示以下错误:
尝试安排带有警报的本地通知,但尚未获得用户显示警报的许可
这意味着您需要注册本地通知。可以使用以下方法实现:
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
您也可以参考博客获取本地通知。
迅速:
您的AppDelegate.swift
文件应如下所示:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert, categories: nil))
return true
}
ViewController.swift
您要在其中创建本地通知的swift文件(例如)应包含以下代码:
//MARK: - Button functions
func buttonIsPressed(sender: UIButton) {
println("buttonIsPressed function called \(UIButton.description())")
var localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 3)
localNotification.alertBody = "This is local notification from Swift 2.0"
localNotification.timeZone = NSTimeZone.localTimeZone()
localNotification.repeatInterval = NSCalendarUnit.CalendarUnitMinute
localNotification.userInfo = ["Important":"Data"];
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.applicationIconBadgeNumber = 5
localNotification.category = "Message"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
//MARK: - viewDidLoad
class ViewController: UIViewController {
var objButton : UIButton!
. . .
override func viewDidLoad() {
super.viewDidLoad()
. . .
objButton = UIButton.buttonWithType(.Custom) as? UIButton
objButton.frame = CGRectMake(30, 100, 150, 40)
objButton.setTitle("Click Me", forState: .Normal)
objButton.setTitle("Button pressed", forState: .Highlighted)
objButton.addTarget(self, action: "buttonIsPressed:", forControlEvents: .TouchDown)
. . .
}
. . .
}
在iOS 9及更低版本中使用本地通知的方式在iOS 10中完全不同。
Apple发行说明的屏幕抓图下方对此进行了描述。
您可以参考Apple参考文档获取UserNotification。
以下是本地通知的代码:
目标C:
在App-delegate.h
文件中使用@import UserNotifications;
应用程序代理应符合UNUserNotificationCenterDelegate
协议
在didFinishLaunchingOptions
下面的代码中使用:
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
[self showAlert];
}
}];
-(void)showAlert {
UIAlertController *objAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"show an alert!" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
NSLog(@"Ok clicked!");
}];
[objAlertController addAction:cancelAction];
[[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YES completion:^{
}];
}
现在在任何视图控制器中创建一个按钮,并在IBAction中使用以下代码:
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@“Notification!” arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@“This is local notification message!“arguments:nil];
objNotificationContent.sound = [UNNotificationSound defaultSound];
// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
// Deliver the notification in five seconds.
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10.f repeats:NO];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@“ten” content:objNotificationContent trigger:trigger];
// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(@“Local Notification succeeded“);
} else {
NSLog(@“Local Notification failed“);
}
}];
斯威夫特3:
AppDelegate.swift
文件中使用import UserNotifications
UNUserNotificationCenterDelegate
协议在didFinishLaunchingWithOptions
下面的代码中使用
// Override point for customization after application launch.
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
if error != nil {
print("Request authorization failed!")
} else {
print("Request authorization succeeded!")
self.showAlert()
}
}
func showAlert() {
let objAlert = UIAlertController(title: "Alert", message: "Request authorization succeeded", preferredStyle: UIAlertControllerStyle.alert)
objAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
//self.presentViewController(objAlert, animated: true, completion: nil)
UIApplication.shared().keyWindow?.rootViewController?.present(objAlert, animated: true, completion: nil)
}
现在在任何视图控制器中创建一个按钮,并在IBAction中使用以下代码:
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "notify-test"
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request)
在appdelegate.m文件中,将以下代码写入applicationDidEnterBackground中以获取本地通知
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:@"Hello world"];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
[application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}
创建本地通知非常简单。只需按照以下步骤。
在viewDidLoad()函数上,向用户询问您的应用希望显示通知的权限。为此,我们可以使用以下代码。
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
})
然后,您可以创建一个按钮,然后在操作功能中可以编写以下代码以显示通知。
//creating the notification content
let content = UNMutableNotificationContent()
//adding title, subtitle, body and badge
content.title = "Hey this is Simplified iOS"
content.subtitle = "iOS Development is fun"
content.body = "We are learning about iOS Local Notification"
content.badge = 1
//getting the notification trigger
//it will be called after 5 seconds
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
//getting the notification request
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
//adding the notification to notification center
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
通知将显示,只需点击通知按钮后单击主页按钮。当应用程序处于前台时,不会显示通知。但是,如果您使用的是iPhoneX。即使应用程序处于前台,您也可以显示通知。为此,您只需要添加一个称为UNUserNotificationCenterDelegate的委托即可。
有关更多详细信息,请访问此博客文章:iOS Local Notification Tutorial
使用Swift 5更新通常,我们使用三种类型的本地通知
您可以在其中发送简单的文本通知或带有操作按钮和附件的位置。
下面的示例在您的应用程序中使用UserNotifications包,以获取通知权限,根据用户操作AppDelegate本身准备和发送通知,并使用列出不同类型的本地通知测试的视图控制器。
AppDelegate
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
let notificationCenter = UNUserNotificationCenter.current()
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//Confirm Delegete and request for permission
notificationCenter.delegate = self
let options: UNAuthorizationOptions = [.alert, .sound, .badge]
notificationCenter.requestAuthorization(options: options) {
(didAllow, error) in
if !didAllow {
print("User has declined notifications")
}
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
//MARK: Local Notification Methods Starts here
//Prepare New Notificaion with deatils and trigger
func scheduleNotification(notificationType: String) {
//Compose New Notificaion
let content = UNMutableNotificationContent()
let categoryIdentifire = "Delete Notification Type"
content.sound = UNNotificationSound.default
content.body = "This is example how to send " + notificationType
content.badge = 1
content.categoryIdentifier = categoryIdentifire
//Add attachment for Notification with more content
if (notificationType == "Local Notification with Content")
{
let imageName = "Apple"
guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else { return }
let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
content.attachments = [attachment]
}
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let identifier = "Local Notification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}
}
//Add Action button the Notification
if (notificationType == "Local Notification with Action")
{
let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive])
let category = UNNotificationCategory(identifier: categoryIdentifire,
actions: [snoozeAction, deleteAction],
intentIdentifiers: [],
options: [])
notificationCenter.setNotificationCategories([category])
}
}
//Handle Notification Center Delegate methods
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
if response.notification.request.identifier == "Local Notification" {
print("Handling notifications with the Local Notification Identifier")
}
completionHandler()
}
}
和ViewController
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var appDelegate = UIApplication.shared.delegate as? AppDelegate
let notifications = ["Simple Local Notification",
"Local Notification with Action",
"Local Notification with Content",]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notifications.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = notifications[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let notificationType = notifications[indexPath.row]
let alert = UIAlertController(title: "",
message: "After 5 seconds " + notificationType + " will appear",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "Okay, I will wait", style: .default) { (action) in
self.appDelegate?.scheduleNotification(notificationType: notificationType)
}
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:@"Hello world"];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
[application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}
这是可行的,但是在iOS 8.0和更高版本中,您的应用程序必须先使用注册用户通知,-[UIApplication registerUserNotificationSettings:]
然后才能安排和显示UILocalNotifications,请不要忘记这一点。
iOS 8及更高版本的用户,请将此内容包含在App委托中以使其正常运行。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)])
{
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
return YES;
}
然后添加以下代码行将有所帮助,
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:@"Hello world"];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
[application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}
-(void)kundanselect
{
NSMutableArray *allControllers = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
NSArray *allControllersCopy = [allControllers copy];
if ([[allControllersCopy lastObject] isKindOfClass: [kundanViewController class]])
{
[[NSNotificationCenter defaultCenter]postNotificationName:@"kundanViewControllerHide"object:nil userInfo:nil];
}
else
{
[[NSUserDefaults standardUserDefaults] setInteger:4 forKey:@"selected"];
[self performSegueWithIdentifier:@"kundansegue" sender:self];
}
}
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ApparelsViewControllerHide) name:@"ApparelsViewControllerHide" object:nil];
我假设您已请求授权并注册了您的应用程序以进行通知。
这是创建本地通知的代码
@available(iOS 10.0, *)
func send_Noti()
{
//Create content for your notification
let content = UNMutableNotificationContent()
content.title = "Test"
content.body = "This is to test triggering of notification"
//Use it to define trigger condition
var date = DateComponents()
date.calendar = Calendar.current
date.weekday = 5 //5 means Friday
date.hour = 14 //Hour of the day
date.minute = 10 //Minute at which it should be sent
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
let uuid = UUID().uuidString
let req = UNNotificationRequest(identifier: uuid, content: content, trigger: trigger)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(req) { (error) in
print(error)
}
}