我想知道我(作爲開發人員)如何設置本地通知,以便在我設置的時候,我的應用程序會生成具有自定義消息的通知/提醒...如何在iPhone應用程序中創建本地通知
回答
在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]];
}
這裏是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發行說明下方的屏幕抓取描述了這一點。
您可以參考apple reference document爲UserNotification。
下面是本地通知代碼:
目的-C:
在
App-delegate.h
文件使用@import UserNotifications;
的App-代表應符合
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
fil e,利用import UserNotifications
- 的appDelegate應符合
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)
我是否需要將funcButtonIsPressed運行於按鈕按下?如果我希望應用程序默認每週發送一次該通知,我應該將它添加到最初的VC的viewDidLoad中嗎? – 2016-02-24 01:08:25
另外,爲什麼你的AppDelegate.swift文件有兩次didFinishLaunchingWithOptions? – 2016-02-24 10:32:49
-(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];
- (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:]
用戶註冊通知,不要忘記這一點。
- [UIApplication registerUserNotificationSettings:]將覆蓋推送通知設置。所以請小心使用推送可執行通知。 – 2016-07-11 09:07:42
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]];
}
創建本地通知是很容易的。只要按照這些步驟。
On 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)
通知將顯示,只需點擊主頁按鈕後點擊通知按鈕。當應用程序處於前臺時,不會顯示通知。但是,如果您使用iPhone X.即使應用程序處於前景中,您也可以顯示通知。對於這一點,你只需要添加一個名爲UNUserNotificationCenterDelegate
欲瞭解更多詳情,請訪問該博客文章代表:iOS Local Notification Tutorial
是否有可能每天都用太平洋時間重複通知並重復,直到應用程序打開? – 2018-02-23 05:00:48
- 1. 構建iPhone應用程序,觸發重複的本地通知
- 2. 如何創建本地化的iPhone應用程序?
- 3. iphone本地通知當應用程序在活動
- 4. 如何在應用程序中實現本地通知警報?
- 5. 如何在Android應用程序(如iPhone)上創建通知圖標徽章
- 6. 創建通用應用程序(IPhone/Ipad)
- 7. 如何從iPhone中刪除應用程序時刪除所有本地通知
- 8. 如何在iPhone/iPad上創建通用應用程序?
- 9. iPhone應用程序崩潰本地通知
- 10. 如何通過應用程序語言本地化iOS通知
- 11. 如何創建iPhone應用程序
- 12. 如何創建iPhone應用程序?
- 13. iPhone應用程序中的通知欄
- 14. 刪除從以前的應用程序版本創建的本地通知
- 15. 我如何在iphone應用程序中推送通知?
- 16. 如何創建應用程序以使用實時通知
- 17. 如何創建通用應用程序?
- 18. 爲iphone和android創建本地web應用程序
- 19. 如何通過我的iPhone應用程序創建鬧鐘
- 20. 如何爲您的Web應用程序創建桌面通知?
- 21. iphone:在本地iPhone應用程序中嵌入Safari(如「框架」)
- 22. 如何在Swift 3中創建/註冊本地通知設置?
- 23. 本地通知只出現在通知中心,當應用程序在iPhone上打開時
- 24. 在iPhone中創建電話應用程序的通話視圖
- 25. 在Android應用程序中創建通知
- 26. 在Adobe AIR中創建通知窗口應用程序
- 27. 如何在Windows Service應用程序中爲用戶創建提示/通知?
- 28. 如何取消本地通知iphone
- 29. iphone中的應用程序本地化
- 30. 如何在iphone中創建應用程序包?
THX。幫助我:D – Vladimir 2014-04-28 07:01:54
當您使用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