IOS极光推送

一、申请证书

具体证书不做详解,主要是记录下在使用推送功能时的一下注意事项:
1、如果没有创建产品appid,创建appid并勾选上Push Noticification 功能:

2、一直到下一步创建证书,在创建证书时,需要创建开发环境下的证书和生产环境中的证书(主要用于发布产品到App store)
3、创建证书的过程:使用mac电脑上的钥匙串访问工具创建证书
a、钥匙串访问--证书助手--从证书颁发机构请求证书--填写开发者账号邮箱--保存到磁盘
b、回到开发者中心,上传刚才的证书到相应的环境中,并下载生成的cer证书,保存到本地,使用钥匙串访问工具打开
如果是使用苹果自带推送到此客户端已经完成:
使用极光推送库实现推送:
c、找到刚才的证书,右键导出该证书为.p12格式,并且需要添加密码
d、登录极光推送官网应用管理,创建应用,上传相应的证书,记录  AppKey 然后根据官方文档填写代码

二、代码编写

1、根据官方文档添加SDK,没难度
2、编写代码

Appdelegate.h
#import <UIKit/UIKit.h>
#import "JPUSHService.h"
#import "RootViewController.h"

static NSString *appKey = @"你的极光推送的id";
static NSString *channel = @"获取应用渠道,一般为app store";
static BOOL isProduction = FALSE; //是否为生产环境

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (nonatomic,retain) UIViewController *viewController;
@property (strong, nonatomic) UIWindow *window;

@end

AppDelegate.m 需要注册远程推送类型


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    //服务端要发送push消息给某一设备还必须知道该设备的deviceToken。应用运行后获取到deviceToken,然后上传给服务器
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories 在IOS8.0之后使用
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    //初始化Jpush
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel apsForProduction:isProduction];
  
    return YES;
}
<pre name="code" class="objc">- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
}

#pragma mark 获取deviceToken

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark 收到通知处理
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // userInfo 就是push消息的Payload
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"userInfo = %@",userInfo);
}
//当注册了Backgroud Modes -> Remote notifications 后,notification 处理函数一律切换到下面函数,后台推送代码也在此函数中调用。
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    
    NSLog(@"收到通知:%@", userInfo);

    
    completionHandler(UIBackgroundFetchResultNewData);
}

//本地通知
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}

 
 3、处理消息响应 
 

在处理收到的消息时,使用的NSNotificationCenter方式,消息机制参考学习内容参考如下地址:

http://www.cnblogs.com/xunziji/p/3257447.html

代码如下:

- (void)viewDidLoad {
//添加能接收自定义消息通知
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidSetup:)
                          name:kJPFNetworkDidSetupNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidClose:)
                          name:kJPFNetworkDidCloseNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidRegister:)
                          name:kJPFNetworkDidRegisterNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidLogin:)
                          name:kJPFNetworkDidLoginNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidReceiveMessage:)
                          name:kJPFNetworkDidReceiveMessageNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(serviceError:)
                          name:kJPFServiceErrorNotification
                        object:nil];
}
- (void)serviceError:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSString *error = [userInfo valueForKey:@"error"];
    NSLog(@"%@", error);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)networkDidSetup:(NSNotification *)notification {
    NSLog(@"%@", [notification userInfo]);
    NSLog(@"已连接");
}

- (void)networkDidClose:(NSNotification *)notification {
    NSLog(@"%@", [notification userInfo]);
    NSLog(@"未连接");
}
- (void)networkDidRegister:(NSNotification *)notification {
    NSLog(@"%@", [notification userInfo]);

    NSLog(@"已注册");
}
- (void)networkDidLogin:(NSNotification *)notification {

    NSLog(@"已登录");
    if ([JPUSHService registrationID]) {
        NSLog(@"get RegistrationID = %@ ",[JPUSHService registrationID]);
    }
}
-(void)networkDidReceiveMessage:(NSNotification *)notification{
    //收到消息处理
    NSDictionary *userInfo = [notification userInfo];
    NSString *title = [userInfo valueForKey:@"title"];
    NSString *content = [userInfo valueForKey:@"content"];
    NSDictionary *extra = [userInfo valueForKey:@"extras"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    
    NSString *currentContent = [NSString
                                stringWithFormat:
                                @"收到自定义消息:%@\ntitle:%@\ncontent:%@\nextra:%@\n",
                                [NSDateFormatter localizedStringFromDate:[NSDate date]
                                                               dateStyle:NSDateFormatterNoStyle
                                                               timeStyle:NSDateFormatterMediumStyle],
                                title, content, extra];
    NSLog(@"%@", currentContent);
    _label.text = currentContent;
}

-(void)<span class="s1" style="font-family: Arial, Helvetica, sans-serif;">dealloc</span><span style="font-family: Arial, Helvetica, sans-serif;">{</span>
    //不再使用通知时移除观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

到此极光推送集成已经算是完成,高级功能还需要参考极光推送官网。


其他信息参考  http://tanqisen.github.io/blog/2013/02/27/ios-push-apns/ 具体原理讲得很清楚,感谢博主。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值