iOS消息推送實(shí)現(xiàn)
客戶(hù)端
** 證書(shū)和權(quán)限的申請(qǐng):***
1 :App必須要推送權(quán)限,申請(qǐng)真機(jī)測(cè)試權(quán)限
2 :對(duì)應(yīng)的appID申請(qǐng)推送證書(shū)
3 :使用推送證書(shū)到處P12證書(shū)給服務(wù)器使用
客戶(hù)端代碼實(shí)現(xiàn):
1:建立我們的推送的項(xiàng)目(注意BundleIdentifier必須和我們推送應(yīng)用的App id一致)
2:在A(yíng)ppDelegate里didFinishLaunchingWithOptions函數(shù)里寫(xiě)
- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
……
//推送的形式:標(biāo)記,聲音,提示
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
return YES;
}
- (void)application:(UIApplication *)applicationdidRegisterForRemoteNotificationsWithDeviceToken:(NSData *)pToken {
NSLog(@"regisger success:%@",pToken);
//注冊(cè)成功,將deviceToken保存到應(yīng)用服務(wù)器數(shù)據(jù)庫(kù)中
}
- (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);
}
服務(wù)器端
服務(wù)端開(kāi)發(fā)的思路都差不多,使用第三方封裝好的包,這個(gè)包如果自己寫(xiě)還是很麻煩的。
這里以pushSharp 為例,一個(gè)開(kāi)源的c#推送代碼
關(guān)鍵代碼說(shuō)明:
var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../id4test_push_aps_development.p12"));//證書(shū)位置
//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")//手機(jī)設(shè)備token
.WithAlert("Hello World!")
.WithBadge(7)
.WithSound("sound.caf"));