IOS成長之路-推送(通過蘋果服務器) – iPhone手機開發技術文章 iPhone軟體開發教學課程

關於推送的機制和推送用到的證書問題在這裡不多說。

 

關於推送的代碼部分:

 

客戶端:

 

1、告訴應用程序,接收push來的消息(當然是放在 didFinishLaunchingWithOptions 方法裡面瞭)

 

 

[cpp] 

[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound];  

 

[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound];

2、完成推送比不可缺的東西:deviceToken ,蘋果推送會根據 deviceToken的值進行推送的操作。deviceToken和全球之內的蘋果設備一一對應的,也就是說它是唯一的。

 

 

 

   

 

[cpp]

– (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {  

    NSLog(@"獲取設備的deviceToken: %@", deviceToken);  

}  

– (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{  

      

    NSLog(@"Failed to get token, error: %@", error);  

 

– (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    NSLog(@"獲取設備的deviceToken: %@", deviceToken);

}

– (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{

    

    NSLog(@"Failed to get token, error: %@", error);

 

 

 

 

3、對推送過來的消息進行處理的方法:

 

 

[cpp] 

– (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo  

  

{  

    //以警告框的方式來顯示推送消息   

    if ([[userInfo objectForKey:@"aps"] objectForKey:@"alert"]!=NULL) {  

        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"經過推送發送過來的消息"  

                                                        message:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]  

                                                       delegate:self  

                                              cancelButtonTitle:@"關閉"  

                                              otherButtonTitles:@"處理",nil];  

        [alert show];  

        [alert release];  

    }  

}  

 

You May Also Like