如何在iOS中创建本地通知? [英] How can I create local notifications in iOS?

查看:88
本文介绍了如何在iOS中创建本地通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何设置本地通知,以便在我设置时,我的应用会生成带有自定义消息的通知/提醒...

解决方案

以下是适用于我的项目的 LocalNotification 的示例代码。



目标 - C:



此代码块在 AppDelegate 文件中:

   - (BOOL)应用程序:(UIApplication *)应用程序didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
[launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
//在应用程序启动后覆盖自定义点。
返回YES;
}

//当应用程序处于前台时(活动模式)调用此代码块
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification * )通知{

UIAlertView * notificationAlert = [[UIAlertView alloc] initWithTitle:@Notification消息:@本地通知
委托:nil cancelButtonTitle:@OkotherButtonTitles:nil ,零];

[notificationAlert show];
// NSLog(@didReceiveLocalNotification);
}

任何 ViewController的.m文件中的此代码块

   - (IBAction)startLocalNotification {//将此方法绑定到UIButton操作
的NSLog(@ startLocalNotification);

UILocalNotification * notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7];
notification.alertBody = @这是本地通知!;
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]];
}

您还可以参考



您可以参考苹果参考文档



以下是本地通知的代码:



目标-C:


  1. App-delegate.h 文件使用 @import UserNotifications;


  2. App -delegate应符合 UNUserNotificationCenterDelegate 协议


  3. didFinishLaunchingOptions 使用以下代码:

      UNUserNotif icationCenter * center = [UNUserNotificationCenter currentNotificationCenter]; 
    [center requestAuthorizationWithOptions :( UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
    completionHandler:^(BOOL授予,NSError * _Nullable错误){
    if(!error){
    NSLog(@请求授权成功!);
    [self showAlert];
    }
    }];

    - (void)showAlert {
    UIAlertController * objAlertController = [UIAlertController alertControllerWithTitle:@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:^ {
    }];

    }


  4. 现在在任何视图控制器中创建一个按钮在IBAction中使用以下代码:

      UNMutableNotificationContent * objNotificationContent = [[UNMutableNotificationContent alloc] init]; 

    objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@Notification!参数:nil];

    objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@这是本地通知消息!参数:nil];

    objNotificationContent.sound = [UNNotificationSound defaultSound];

    // 4.更新应用程序图标徽章编号
    objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);

    //在五秒钟内发送通知。
    UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10.f重复:否];

    UNNotificationRequest * request = [UNNotificationRequest requestWithIdentifier:@tencontent:objNotificationContent trigger:trigger];

    // 3.安排localNotification
    UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];

    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error){
    if(!error){
    NSLog(@Local Notification succeeded);
    } else {
    NSLog(@本地通知失败);
    }
    }];


Swift 3:


  1. AppDelegate.swift 文件中使用 import UserNotifications

  2. Appdelegate应符合 UNUserNotificationCenterDelegate 协议

  3. didFinishLaunchingWithOptions 使用下面的代码

      //覆盖自定义后的点申请发布。 
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options:[.alert,.sound]){$ grant,error}
    //启用或禁用基于授权的功能。
    if error!= nil {
    print(请求授权失败!)
    } else {
    print(请求授权成功!)
    self.showAlert ()
    }
    }


    func showAlert(){
    让objAlert = UIAlertController(标题:警告,消息:请求授权成功,preferredStyle:UIAlertControllerStyle.alert)

    objAlert.addAction(UIAlertAction(标题:OK,样式:UIAlertActionStyle.default,handler:nil))
    //self.presentViewController(objAlert ,动画:true,完成:nil)

    UIApplication.shared()。keyWindow?.rootViewController?.present(objAlert,animated:true,completion:nil)
    }


  4. 现在在任何视图控制器中创建一个按钮,在IBAction中使用以下代码:

      let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey:Hello!,参数:nil)
    content.bod y = NSString.localizedUserNotificationString(forKey:Hello_message_body,参数:nil)
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier =notify-test

    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval:5,repeat:false)
    let request = UNNotificationRequest.init(identifier:notify-test,content:content,trigger:trigger)

    let center = UNUserNotificationCenter.current()
    center.add(request)



I would like to know how I can setup local notifications so that at the time I set, my app generates a notification/alert with a customized message...

解决方案

Here is sample code for LocalNotification that worked for my project.

Objective-C:

This code block in AppDelegate file :

- (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");
    }

This code block in .m file of any 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];    
}

The above code display an AlertView after time interval of 7 seconds when pressed on button that binds startLocalNotification If application is in background then it displays BadgeNumber as 10 and with default notification sound.

This code works fine for iOS 7.x and below but for iOS 8 it will prompt following error on console:

Attempting to schedule a local notification with an alert but haven't received permission from the user to display alerts

This means you need register for local notification. This can be achieved using:

if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){

    [application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}

You can also refer blog for local notification.

Swift:

You AppDelegate.swift file should look like this:

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
}

The swift file (say ViewController.swift) in which you want to create local notification should contain below code:

//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)

        . . .
    }

    . . .
}

The way you use to work with Local Notification in iOS 9 and below is completely different in iOS 10.

Below screen grab from Apple release notes depicts this.

You can refer apple reference document for UserNotification.

Below is code for local notification:

Objective-C:

  1. In App-delegate.h file use @import UserNotifications;

  2. App-delegate should conform to UNUserNotificationCenterDelegate protocol

  3. In didFinishLaunchingOptions use below code:

    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:^{            
        }];
    
    }
    

  4. Now create a button in any view controller and in IBAction use below code :

    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");
        }
    }];
    

Swift 3:

  1. In AppDelegate.swift file use import UserNotifications
  2. Appdelegate should conform to UNUserNotificationCenterDelegate protocol
  3. In didFinishLaunchingWithOptions use below code

    // 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)
    }
    

  4. Now create a button in any view controller and in IBAction use below code :

    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)
    

这篇关于如何在iOS中创建本地通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆