iOS消息推送實現
客戶端
** 證書和權限的申請:***
1 :App必須要推送權限,申請真機測試權限
2 :對應的appID申請推送證書
3 :使用推送證書到處P12證書給服務器使用
客戶端代碼實現:
1:建立我們的推送的項目(注意BundleIdentifier必須和我們推送應用的App id一致)
2:在AppDelegate里didFinishLaunchingWithOptions函數里寫
- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
……
//推送的形式:標記,聲音,提示
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
return YES;
}
- (void)application:(UIApplication *)applicationdidRegisterForRemoteNotificationsWithDeviceToken:(NSData *)pToken {
NSLog(@"regisger success:%@",pToken);
//注冊成功,將deviceToken保存到應用服務器數據庫中
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
// 處理推送消息
NSLog(@"userinfo:%@",userInfo);
NSLog(@"收到推送消息:%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]);
}
- (void)application:(UIApplication *)applicationdidFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"Registfail%@",error);
}
服務器端
服務端開發的思路都差不多,使用第三方封裝好的包,這個包如果自己寫還是很麻煩的。
這里以pushSharp 為例,一個開源的c#推送代碼
關鍵代碼說明:
var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../id4test_push_aps_development.p12"));//證書位置
//IMPORTANT: If you are using a Development provisioning Profile, you must use the Sandbox push notification server
// (so you would leave the first arg in the ctor of ApplePushChannelSettings as 'false')
// If you are using an AdHoc or AppStore provisioning profile, you must use the Production push notification server
// (so you would change the first arg in the ctor of ApplePushChannelSettings to 'true')
push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "WEIWEI")); //Extension method
//Fluent construction of an iOS notification
//IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets generated within your iOS app itself when the Application Delegate
// for registered for remote notifications is called, and the device token is passed back to you
push.QueueNotification(new AppleNotification()
.ForDeviceToken("cde6d75a0fc144b2bd30e10e15855376e4b53d793e6ccf9495787df19ace48d4")//手機設備token
.WithAlert("Hello World!")
.WithBadge(7)
.WithSound("sound.caf"));