2011-05-18 76 views

回答

50

在appdelegate.m文件寫入applicationDidEnterBackground的follwing代碼來獲取本地通知

- (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]]; 
} 
+0

THX。幫助我:D – Vladimir 2014-04-28 07:01:54

+9

當您使用setScheduledLocalNotifications安排一個通知時:不必要。有一個 scheduleLocalNotification方法需要一個參數 - 要安排的通知。 https://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIApplication_Class/index.html#//apple_ref/occ/instm/UIApplication/scheduleLocalNotification: – 2014-09-25 15:28:31

72

這裏是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"); 
    } 

在任何ViewController的.m文件此代碼塊:

-(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 0如果應用程序在後臺,則它會將BadgeNumber顯示爲10,並顯示默認通知聲音。

此代碼工作正常的iOS 7.x及以下但的iOS 8系統會提示在控制檯下面的錯誤

試圖安排與警報本地通知,但還沒有收到許可從用戶到顯示警報

這意味着您需要註冊本地通知。這可以通過以下方式實現:

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

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

您也可以參考blog進行本地通知。

斯威夫特:

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)要在其中創建本地通知應包含以下代碼:

//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發行說明下方的屏幕抓取描述了這一點。

Screenshot

您可以參考apple reference document爲UserNotification。

下面是本地通知代碼:

目的-C:

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

  2. 的App-代表應符合UNUserNotificationCenterDelegate協議

  3. 在以下代碼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:^{    
        }]; 
    
    } 
    
  4. 現在,在任何視圖控制器創建一個按鈕,並在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:

  1. AppDelegate.swift fil e,利用import UserNotifications
  2. 的appDelegate應符合UNUserNotificationCenterDelegate協議
  3. 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) 
    } 
    
  4. 現在,在任何視圖控制器創建一個按鈕,並在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) 
    
+1

我是否需要將funcButtonIsPressed運行於按鈕按下?如果我希望應用程序默認每週發送一次該通知,我應該將它添加到最初的VC的viewDidLoad中嗎? – 2016-02-24 01:08:25

+1

另外,爲什麼你的AppDelegate.swift文件有兩次didFinishLaunchingWithOptions? – 2016-02-24 10:32:49

0
-(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];

1
- (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及更高版本,您的應用程序必須能夠安排和目前UILocalNotifications之前使用-[UIApplication registerUserNotificationSettings:]用戶註冊通知,不要忘記這一點。

+0

- [UIApplication registerUserNotificationSettings:]將覆蓋推送通知設置。所以請小心使用推送可執行通知。 – 2016-07-11 09:07:42

0

iOS 8用戶及以上,請包括在應用程序委託,使其工作。

- (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]]; 

} 
1

創建本地通知是很容易的。只要按照這些步驟。

  1. On viewDidLoad()函數詢問用戶您的應用程序想要顯示通知的權限。爲此我們可以使用下面的代碼。

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in 
    }) 
    
  2. 然後你就可以創建一個按鈕,然後在操作功能,你可以寫下面的代碼顯示通知。

    //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) 
    
  3. 通知將顯示,只需點擊主頁按鈕後點擊通知按鈕。當應用程序處於前臺時,不會顯示通知。但是,如果您使用iPhone X.即使應用程序處於前景中,您也可以顯示通知。對於這一點,你只需要添加一個名爲UNUserNotificationCenterDelegate

欲瞭解更多詳情,請訪問該博客文章代表:iOS Local Notification Tutorial

+0

是否有可能每天都用太平洋時間重複通知並重復,直到應用程序打開? – 2018-02-23 05:00:48

相關問題