蘋果APNS在app中的具體實現

來源:互聯網
上載者:User

標籤:apns   推送   

鑒於伺服器穩定的開發難度很大,小團隊不建議自己開發,建議使用穩定的第三方推送方案,如個推,蝴蝶等。
要想使用蘋果APNS推送訊息,首先要把開發app的xcode所用認證上傳到伺服器上,當然你的認證要用的是hot認證或勾選push選項的發行者,普通研發者認證是收不到push訊息的。
安裝認證到服務端
你應該安裝SSL認證和私匙到你的provider程式啟動並執行伺服器上。
步驟如下:
0.安裝該認證到mac電腦的鑰匙串。
1.開啟鑰匙串,在左側面板上點擊我的認證欄。
2.找到這個SSL認證,展開會看到認證和私匙。
3.我們選中認證和私匙,然後匯出為”個人資訊分頁檔”–即副檔名為p12的檔案。
4.provider伺服器程式最好用Ruby和Perl這類語言,可以方便的處理”個人資訊分頁檔”裡的認證。mac下開啟終端輸入以下命令以把認證轉換為這類語言樂於交流的格式:
openssl pkcs12 -in CertificateName.p12 -out CertificateName.pem -nodes
5.把這pem檔案拷到伺服器上並安裝到某個適當的位置。
說完服務端了就具體說用戶端吧,首先在AppDelegate.m(AppDelegate.mm)檔案中的- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions加入[AppDelegate registerForRemoteNotification];來重新擷取裝置相關的token,不要緩衝token.
當登出時,本賬戶在別的裝置上登陸時(被踢掉)或者捕獲到被拉掉事件時(- (void)applicationWillTerminate:(UIApplication *)application)需要取消推送的註冊,代碼如[[UIApplication sharedApplication] unregisterForRemoteNotifications];//使用者退出登入後,取消推送的註冊,登入時register,當然退出到登陸頁面後登陸成功後還時需要重新進行推送的註冊。
在didReceiveRemoteNotification可以處理收到的訊息,可以只記錄到全域變數裡暫時不操作,也可以播放鈴聲,震動,彈出對話方塊,跳轉頁面等。像這個版本更新的push訊息處理就沒有告知使用者 if([type isEqualToString:@”psy_needUpgrade”])
{
NSString *url = [page objectForKey:@”downloadUrl”];
if(url != nil)
{
g_needUpgrade = 1;
g_downloadUrl = url;
}
return;
}
下面這段代碼是對接收的push訊息進行處理。

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{    FLDDLogDebug(@"push userinfo:%@", userInfo);    NSDictionary *aps = [userInfo objectForKey:@"aps"];    NSInteger count = [[aps objectForKey:@"badge"] toInt];    [application setApplicationIconBadgeNumber:count];    NSString *alert = [aps objectForKey:@"alert"];    NSDictionary *page = [userInfo objectForKey:@"page"];    NSString *actionId = [page objectForKey:@"id"];    NSString *type = [page objectForKey:@"type"];    NSString *title = [page objectForKey:@"title"];    NSString *notifyType = [[page objectForKey:@"notifyType"] toString];    NSString *subType = [[page objectForKey:@"subType"] toString];    NSString *subId = [[page objectForKey:@"subId"] toString];//app訊息對應的訂單id    NSString *phone = [page objectForKey:@"userTel"];    NSString *userPhone = [User currentUser].phone;    if (![phone isEqualToString:userPhone]) {        return;    }    if([type isEqualToString:@"psy_needUpgrade"])    {        NSString *url = [page objectForKey:@"downloadUrl"];        if(url != nil)        {            g_needUpgrade = 1;            g_downloadUrl = url;        }        return;    }    if ([notifyType isEqualToString:@"1"]) {        type = kFhlappnotify;    }    else if ([notifyType isEqualToString:@"2"]){        type = kFhlordernotify;    }    if ([type isEqualToString:kFhlGrab]) {        //set home refresh tag        [[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_HOME_NOTIFICATION object:nil];    }    if (application.applicationState == UIApplicationStateActive) {        [application setApplicationIconBadgeNumber:0];        if ([AppManager boolValueForKey:@"shock"]) {            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);        }        else {            [self playAudioWithIndex:type];        }        if ([type isEqualToString:kFhllogout]) {            g_loginStat = LOGIN_STATE_EXIT_LOGIN;            //            [AppManager saveCurrentOrderRemind];            [[UIApplication sharedApplication] unregisterForRemoteNotifications];            [[User currentUser] removeUserInfo];            [AppManager setUserDefaultsValue:@"" key:@"telephone"];            [AppManager setUserDefaultsValue:@"" key:@"password"];            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil                                                                message:alert                                                               delegate:self                                                      cancelButtonTitle:@"確定"                                                      otherButtonTitles:nil, nil];            alertView.tag = 1005;            [alertView show];        }        else if ([type isEqualToString:kFhlGrab]) {            //set home refresh tag            //            [AppManager setUserBoolValue:YES key:@"NeedRefreshHome"];        }        else if ([type isEqualToString:kFhlSend] || [type isEqualToString:kFhlReceived]) {            //            Order *order = [[Order alloc] init];            //            order.id = actionId;            //            [[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_ORDER_NOTIFICATION object:nil userInfo:@{@"Order" : order, @"Option" : @(3)}];        }        else if ([type isEqualToString:kFhlBeAppoint]) {            Order *order = [[Order alloc] init];            order.id = subId;            [[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_ORDER_NOTIFICATION object:nil userInfo:@{@"Order" : order, @"Option" : @(3)}];        }        else {            if ([subType isEqualToString:kFhlSubClosed] || [subType isEqualToString:kFhlSubRejected]) {                Order *order = [[Order alloc] init];                order.id = subId;                if ([subType isEqualToString:kFhlSubRejected]) {                    order.state = @"50";                }                [[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_ORDER_NOTIFICATION object:nil userInfo:@{@"Order" : order, @"Option" : @(3)}];            }            if ([type isEqualToString:kFhlcancel]) {                Order *order = [[Order alloc] init];                order.id = actionId;                [[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_ORDER_NOTIFICATION object:nil userInfo:@{@"Order" : order, @"Option" : @(4)}];            }            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title                                                                message:alert                                                               delegate:self                                                      cancelButtonTitle:@"忽略"                                                      otherButtonTitles:@"進入", nil];            if (type.length > 0 && actionId.length > 0) {                objc_setAssociatedObject(alertView, &AlertAssociatedKey,@{@"type" : type, @"actionId" : actionId}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);            }            [alertView show];        }    }    else if (application.applicationState == UIApplicationStateInactive){        [self pushViewControllerWithType:type actionId:actionId];    }}

下面這斷代碼就是具體的推送的註冊:

“`
+ (void)registerForRemoteNotification {

FLDDLogDebug(@"*\n*\n*\nregisterForRemoteNotification\n*\n*\n*\n");if (IOS8_OR_LATER) {    UIUserNotificationType types = UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIRemoteNotificationTypeNewsstandContentAvailability;    UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];} else {    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeNewsstandContentAvailability)];}

}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

蘋果APNS在app中的具體實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.