在代码中注册推送
在工程中打开AppDelegate.m (Xcode不同版本 可能为XXXXAppDelegate.m)
在.m中添加如下代码:
-(BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{//注册推送功能 (推送的三种类型)
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
//判断程序是不是由推送服务完成的
if (launchOptions)
{
NSDictionary* pushNotificationKey = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (pushNotificationKey)
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"推送通知" message:@"这是通过推送窗口启动的程序,你可以在这里处理推送内容" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
//用来获取设备 ID 一会要用到。
NSLog(@"Device Token = %@",deviceToken);
}
第一个方法中 :
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"推送通知" message:@"这是通过推送窗口启动的程序,你可以在这里处理推送内容" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
是用来处理程序是因推送打开的时候 执行如上代码。
第二个方法中:
NSLog(@"Device Token = %@",deviceToken);
用来输出设备的ID号,等下我们测试需要用到。
添加完代码之后运行 看到Log中显示设备ID:
复制< >中间的设备ID
打开附件中的PushMeBaby.zip 这是一个可以向苹果APNS 服务器发送推送信息的小程序。 我们需要用它来做一个模拟的推送。
解压PushMeBady后 打开这个工程。
把刚才下载的anps.cer 替换工程中的anps.cer。
打开ApplicationDelegate.m。
修改self.deviceToken 的值为 刚刚程序Log中的那个设备ID。
好了,这里基本上就可以测试程序的推送功能了。
运行PushMeBaby 工程, 第一次运行的时候有一个提示,选择总是允许。
点击Push 这时查看你的设备。(如果没有响应,可以重新编译一下iOS的工程。)
到这里,推送就可以使用PushMeBaby 来传达至用户的设备上了。