標籤:des style blog http io ar color os 使用
Push的原理:
Push 的工作機制可以簡單的概括為:Provider是指某個iPhone軟體的Push伺服器,這篇文章我將使用.net作為Provider。APNS 是Apple Push Notification Service(Apple Push伺服器)的縮寫,是蘋果的伺服器。可以分為三個階段。第一階段:Push伺服器應用程式把要發送的訊息、目的iPhone的標識打包,發給APNS。第二階段:APNS在自身的登入Push服務的iPhone列表中,尋找有相應標識的iPhone,並把訊息發到iPhone。第三階段:iPhone把發來的訊息傳遞給相應的應用程式, 並且按照設定彈出Push通知。 iOS前端push訊息步驟:1.應用程式註冊訊息通知,代碼如下:[注意嘍:ios7和ios8註冊通知是不一樣的哦!!!]
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ //訊息推送 [self msgPush];}/** 訊息推送 **/- (void) msgPush{ //推送的形式:標記,聲音,提示 if (IS_IOS8) { //1.建立訊息上面要添加的動作(按鈕的形式顯示出來) UIMutableUserNotificationAction *action = [[UIMutableUserNotificationAction alloc] init]; action.identifier = @"action";//按鈕的標示 [email protected]"Accept";//按鈕的標題 action.activationMode = UIUserNotificationActivationModeForeground;//當點擊的時候啟動程式 // action.authenticationRequired = YES; // action.destructive = YES; UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init]; action2.identifier = @"action2"; [email protected]"Reject"; action2.activationMode = UIUserNotificationActivationModeBackground;//當點擊的時候不啟動程式,在幕後處理 action.authenticationRequired = YES;//需要解鎖才能處理,如果action.activationMode = UIUserNotificationActivationModeForeground;則這個屬性被忽略; action.destructive = YES; //2.建立動作(按鈕)的類別集合 UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init]; categorys.identifier = @"alert";//這組動作的唯一標示,推播通知的時候也是根據這個來區分 [categorys setActions:@[action,action2] forContext:(UIUserNotificationActionContextMinimal)]; //3.建立UIUserNotificationSettings,並設定訊息的顯示類類型 UIUserNotificationSettings *notiSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIRemoteNotificationTypeSound) categories:[NSSet setWithObjects:categorys, nil]]; [[UIApplication sharedApplication] registerUserNotificationSettings:notiSettings]; }else{ [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert]; } }
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
//註冊遠程通知
[application registerForRemoteNotifications];
}
2、 IOS跟APNS Server要deviceToken。應用程式接受deviceToken。【代碼如下:】
3、應用程式將deviceToken發送給PUSH服務端程式
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{ MyLog(@"myToken = %@",deviceToken); //儲存token [Config saveToken:[NSString stringWithFormat:@"%@",deviceToken]];
//將deviceToken發送給伺服器
[self initNetworkState:[NSString stringWithFormat:@"%@",deviceToken]];
}
-(void)initNetworkState:(NSString *)pToken
{
NSDictionary *dicJson = [PackJsonForMine packTokenJson:pToken];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJson options:NSJSONWritingPrettyPrinted error: &error];
NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:IDS_URL_TOKEN]];
[request setRequestMethod:@"POST"];
[request setPostBody:tempJsonData];
[request setDelegate:self];
[request setDidFailSelector:@selector(requestLogFailed:)];
[request setDidFinishSelector:@selector(requestLogFinish:)];
[request startAsynchronous];
}
/**
發送token失敗
**/
- (void)requestLogFailed:(ASIHTTPRequest *)requests
{
MyLog(@"發送token到伺服器失敗%@",[requests responseString]);
}
/**
發送token成功
**/
- (void)requestLogFinish:(ASIHTTPRequest *)requests
{
[Config saveTokenFlag];
}
4、服務端程式向APNS服務發送訊息。5、APNS服務將訊息發送給iPhone應用程式。【注意嘍:處理推送分為兩種:正在啟動並執行程式收到推送訊息,alerat彈窗;鎖屏時通知欄顯示】
#pragma mark - 處理推送的訊息內容- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{ self.urlStr = [userInfo valueForKey:@"link"]; self.message = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]; [UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber = [[[userInfo objectForKey:@"aps"] objectForKey:@"badge"] intValue]; //注意:在開啟應用的時候,是需要一個彈框提醒的,不然使用者看不到推送訊息 if (application.applicationState == UIApplicationStateActive) { if (self.urlStr.length > 0) { CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init]; //自訂AlertView [alertView setContainerView:[self createView]]; [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"關閉",@"查看", nil]]; [alertView setBackgroundColor:[UIColor clearColor]]; [alertView setDelegate:self]; [alertView setUseMotionEffects:true]; [alertView show]; }else{ CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init]; //自訂AlertView [alertView setContainerView:[self createView]]; [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"關閉", nil]]; [alertView setBackgroundColor:[UIColor clearColor]]; [alertView setDelegate:self]; [alertView setUseMotionEffects:true]; [alertView show]; } }else{ if (self.urlStr.length > 0) { WebViewController *webViewC = [[WebViewController alloc] init]; webViewC.link = self.urlStr; [Tool showHideToolBar:HIDE]; [navIntergralController pushViewController:webViewC animated:YES]; } } }
無論是iPhone用戶端跟APNS,還是Provider和APNS都需要通過認證進行串連的。下面介紹一下所用到認證的製作。
一、CSR檔案
1、產生Certificate Signing Request(CSR)2.填寫你的郵箱和常用名稱,並儲存到硬碟點擊繼續:這樣就在本地產生了一個PushTest.certSigningRequest檔案。二、SSL certificate檔案 以及相關的認證製作過程詳情請見如下部落格內容: http://www.cnblogs.com/imlucky/p/3419581.html 在推送中測試的時候需要測試的.P12檔案和發布的.P12檔案 後台代碼:六、JAVA後台代碼:public static void main(String[] args) throws Exception
{
try
{
//從用戶端擷取的deviceToken,在此為了測試簡單,寫固定的一個測試裝置標識。
String deviceToken = "df779eda 73258894 5882ec78 3ac7b254 6ebc66fe fa295924 440d34ad 6505f8c4" System.out.println("Push Start deviceToken:" + deviceToken);
//定義訊息模式
PayLoad payLoad = new PayLoad();
payLoad.addAlert("this is test!");
payLoad.addBadge(1);//訊息推送標記數,小紅圈中顯示的數字。
payLoad.addSound("default");
//註冊deviceToken
PushNotificationManager pushManager = PushNotificationManager.getInstance();
pushManager.addDevice("iPhone", deviceToken);
//串連APNS
String host = "gateway.sandbox.push.apple.com";
//String host = "gateway.push.apple.com";
int port = 2195; String certificatePath = "c:/PushTest.p12";//前面產生的用於JAVA後台串連APNS服務的*.p12檔案位置
String certificatePassword = "123456";//p12檔案密碼。
pushManager.initializeConnection(host, port, certificatePath, certificatePassword, SSLConnectionHelper.KEYSTORE_TYPE_PKCS12);
//發送推送
Device client = pushManager.getDevice("iPhone");
System.out.println("推送訊息: " + client.getToken()+"\n"+payLoad.toString() +" ");
pushManager.sendNotification(client, payLoad);
//停止串連APNS
pushManager.stopConnection();
//刪除deviceToken
pushManager.removeDevice("iPhone");
System.out.println("Push End");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}至此大功告成!!!!!!!
iOS APNS推送前端和後端(Java)代碼