首先 我們先拖拽一個switch控件 并將其與 ViewController.m 關(guān)聯(lián),以方便我們以下的操作
1 我們現(xiàn)在 ViewController.m 中 為其設(shè)置一個全局變量并初始化
@interface ViewController ()
{
UIApplication *app;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
app = [UIApplication sharedApplication];
}
2 我們在switch方法中寫具體的代碼
- (IBAction)changed:(id)sender
{
UISwitch *sw = (UISwitch *)sender;
if (sw.on)
{
if ([UIApplication instanceMethodForSelector:@selector(registerUserNotificationSettings:)])
{
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
// 創(chuàng)建一個本地通知
UILocalNotification *not = [[UILocalNotification alloc] init];
// 設(shè)置觸發(fā)時間
not.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
// 時區(qū)
not.timeZone = [NSTimeZone defaultTimeZone];
// 時間間隔
not.repeatInterval = kCFCalendarUnitMinute;
// 通知聲音
not.soundName = @"gu.mp3";
// 標(biāo)題
not.alertTitle = @"通知來嘍";
// 內(nèi)容
not.alertBody = @"親,上線有好禮喲,快來上線吧";
// 提醒數(shù)字
not.applicationIconBadgeNumber = 1;
// 攜帶額外信息
NSDictionary *info = @{@"jyh":@"key"};
not.userInfo = info;
// 調(diào)度通知
[app scheduleLocalNotification:not];
}
else
{
NSArray *localArray = [app scheduledLocalNotifications];
if (localArray)
{
for (UILocalNotification *noti in localArray)
{
NSDictionary *dict = noti.userInfo;
if (dict)
{
// 如果找到要取消的通知
NSString *inkey = [dict objectForKey:@"jyh"];
if ([inkey isEqualToString:@"key"])
{
[app cancelLocalNotification:noti];
}
}
}
}
}
}
// 第一個判斷是判斷switch 在打開時和關(guān)閉時
// 在switch打開時的第二個判斷是因為版本的問題是否能回應(yīng)registerUserNotificationSettings方法
3 緊接著 我們可以在AppDelegate.m中寫如下代碼
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
application.applicationIconBadgeNumber = 0;
[[[UIAlertView alloc] initWithTitle:@"收到通知"
message:notification.alertBody
delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil] show];
}
這就是在oc中實現(xiàn)本地通知的一個簡單的方法