[applicationregisterForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge|
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
这段代码会在用户第一次安装应用的时候告知用户是否要接受推送。
之后再在这个文件中加入如下代码:
-(void)application:(UIApplication*)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
// Convertthe token to a hex string and make sure it's all caps
NSMutableString *tokenString = [NSMutableStringstringWithString:[[deviceTokendescription] uppercaseString]];
[tokenStringreplaceOccurrencesOfString:@"<"withString:@""options:0range:NSMakeRange(0,tokenString.length)];
[tokenStringreplaceOccurrencesOfString:@">"withString:@""options:0range:NSMakeRange(0,tokenString.length)];
[tokenStringreplaceOccurrencesOfString:@" "withString:@""options:0range:NSMakeRange(0,tokenString.length)];
NSLog(@"Token: %@", tokenString);
// Create theNSURL for the request
NSString *urlFormat =@"https://go.urbanairship.com/api/device_tokens/%@";
NSURL*registrationURL = [NSURLURLWithString:[NSString stringWithFormat:
urlFormat, tokenString]];
// Create theregistration request
NSMutableURLRequest *registrationRequest =[[NSMutableURLRequest alloc]
initWithURL:registrationURL];
[registrationRequestsetHTTPMethod:@"PUT"];
// And fireit off
NSURLConnection *connection = [NSURLConnectionconnectionWithRequest:registrationRequest
delegate:self];
[connectionstart];
// TODO: Passthe token to our server
NSLog(@"We successfully registered forpush notifications");
}
- (void)connection:(NSURLConnection*)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge
{
// Check forprevious failures
if([challenge previousFailureCount] >0)
{
// We've already tried - something iswrong with our credentials
NSLog(@"UrbanAirship credentials invalid");
return;
}
// Send ourUrban Airship credentials
NSURLCredential *airshipCredentials= [NSURLCredential credentialWithUser:@"这里需要填写ApplicationKey"
password:@"这里填ApplicationSecret"
persistence:NSURLCredentialPersistenceNone];
[[challengesender] useCredential:airshipCredentials
forAuthenticationChallenge:challenge];
}
最后这段代码中所需的ApplicationKey和ApplicationSecret会在你刚才创建的Urban Airship网站的应用Detail页面找到,如图:
之后就可以运行编译软件了。成功的话会在output窗口显示We successfully registered for pushnotifications和Device token。
现在再回到Urban Airship的页面。刷新一下,看看Details页面中的Devicetokens一项是不是变成了1.如果是的话,表示你的手机已经成功在服务器上注册了。
点击页面左边工具栏中的PUSH项,试试发送一条推送信息
Test Push Notifications的意思是通过指定的Device token推送信息,如图:
点击Send it!成功了有木有! 最后有一点,就是在进行production推送的时候需要输入信用卡号,不用紧张,只要每月推送量小于一百万条的时候是不会扣费的,呵呵。