你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> ios (推送)之本地推送

ios (推送)之本地推送

編輯:IOS開發綜合

iOS上有兩種消息通知,一種是本地消息(Local Notification),一種是遠程消息(Push Notification,也叫Remote Notification),設計這兩種通知的目的都是為了提醒用戶,現在有些什麼新鮮的事情發生了,吸引用戶重新打開應用。本地推送也可以通過服務器控制,比如說如果有新消息了,推送消息,但是,前提是程序必須是打開的,而遠程推送,是通過蘋果APNS服務器,推送給手機,手機在推送給具體的哪個程序,一般遠程推送用到的比較多,先介紹下本地推送,下節在介紹遠程推送。

本地推送:

首先,先在appdelegate中注冊:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];//注冊本地推送
    
    // Override point for customization after application launch.
    return YES;
}

然後,在具體的viewcontroller中實現推送:

- (IBAction)localPushNow:(id)sender {
 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //本地推送
        UILocalNotification*notification = [[UILocalNotification alloc]init];
        NSDate * pushDate = [NSDate dateWithTimeIntervalSinceNow:10];
        if (notification != nil) {
            notification.fireDate = pushDate;
            notification.timeZone = [NSTimeZone defaultTimeZone];
            notification.repeatInterval = kCFCalendarUnitDay;
            notification.soundName = UILocalNotificationDefaultSoundName;
            notification.alertBody = @"hello,world";
            notification.applicationIconBadgeNumber = 0;
            NSDictionary*info = [NSDictionary dictionaryWithObject:@"test" forKey:@"name"];
            notification.userInfo = info;
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
            
        }
    });

}

在appdelegate中會接收到推送信息:

//接收本地推送

//接收本地推送
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    NSLog(@"%@",notification.alertBody);
    UILabel*label = [[UILabel alloc]init];
    label.frame = CGRectMake(0, 0, 160, 20);
    label.layer.cornerRadius = 10;
    label.backgroundColor = [UIColor blackColor];
    label.text = notification.alertBody;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:12];
    label.textAlignment = NSTextAlignmentCenter;
    
    [self.window addSubview:label];
}

過程中可能會出現如下狀況:

Attempting to schedule a local notification……with a sound but haven't received permission from the user to play sounds

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

可能是因為你沒有注冊,或者設置中沒有開啟推送功能,

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved