PushSharp是一個C#編寫的服務端類庫,用於推送消息到各種客戶端,支持iOS(iPhone/iPad)、Android、Windows Phone、Windows 8、Amazo、Blackberry等設備。
官方網站:https://github.com/Redth/PushSharp
當前最新穩定版本為2.0.4,支持通過NuGet獲取(https://www.nuget.org/packages/PushSharp/)
主要特點
提供了易於使用的API,支持以下平台的消息推送:
- Apple (APNS – iPhone, iPad, OSX 10.8+):APNS即Apple Push Notification Service,詳見:https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html
- Android (GCM/C2DM - 手機及平板):GCM即Google Cloud Message,詳見:http://developer.android.com/google/gcm/index.html
- Chrome (GCM)
- Amazon (ADM):ADM即Amazon Device Messaging,詳見:https://developer.amazon.com/sdk/adm/setup.html
- Windows Phone 7/7.5/8(包括FlipTile,CycleTile及IconicTile模板):詳見:http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402558(v=vs.105).aspx
- Windows 8
- Blackberry (BIS and BES via PAP): 詳見:http://docs.blackberry.com/en/developers/deliverables/51382/
- Firefox OS (即將支持)
100%的托管代碼完全兼容Mono平台。
安裝
PushSharp主要包含以下程序集:
- PushSharp.Core:(必選)核心組件
- PushSharp.Apple:APNS,用於iOS及OSX
- PushSharp.Android:C2DM及GCM,用於Android設備
- PushSharp.Windows:用於Windows 8
- PushSharp.WindowsPhone:用於WP設備
- PushSharp.Amazon.Adm:用於Amazon的設備
- PushSharp.Blackberry:用於黑莓設備
- PushSharp.Google.Chrome:用於Chrome
其中,PushSharp.Core為必須的組件,其他的可以根據自己需要來選擇對應平台。
平常使用只需要用NuGet來獲取程序集即可:
Install-Package PushSharp
這樣會把主流平台的程序集(Apple/Android/Windows/WindowsPhone)都下載下來,可以根據自己需要刪除用不到的平台組件。
假如需要使用Blackberry等NuGet包里沒有的組件,則需要到官方網站(https://github.com/Redth/PushSharp)獲取源碼自行編譯。
對於Apple平台,只需要PushSharp.Core和PushSharp.Apple組件即可。
證書配置
官方WIKI提供了詳細的證書配置步驟:
- Apple平台的證書配置:https://github.com/Redth/PushSharp/wiki/How-to-Configure-&-Send-Apple-Push-Notifications-using-PushSharp
- Android平台的證書配置(使用GCM情況下):https://github.com/Redth/PushSharp/wiki/How-to-Configure-&-Send-GCM-Google-Cloud-Messaging-Push-Notifications-using-PushSharp
Apple平台證書創建流程:
- 創建AppID
- 為AppID配置用於APP簽名的證書:分別有開發環境(Development)和生產環境(Production)的證書
- 編輯AppID啟用消息推送
- 為AppID創建用於消息推送(APNS)的證書(包括Development和Production)
- 下載以上證書並安裝到Key Chain(鑰匙串)
- 導出用於消息推送(APNS)的證書為.p12格式,並為它設置密碼:用於在服務端推送消息
對於Apple平台需要特別說明:
- Provisioning Protal現在已經變成了Certificates, Identifiers & Profiles,可以從Member Center點進去或者iOS Developer Center找到
- 對於已經發布的APP要啟用消息推送功能,需要在Identifiers – App IDs找到對應的ID創建好APNS證書之后,再重新生成用於APP簽名的證書,否則用於注冊消息推送的代碼(RegisterForRemoteNotificationTypes)不會正常工作,即返回的deviceToken為null
- 在使用Development證書調試應用程序時服務端需要使用Development APNS證書來推送消息,使用Production證書發布到AppStore后推送消息需要使用Production APNS證書來推送消息
客戶端啟用消息推送
啟用消息推送都是在AppDelegate里注冊來完成的。
對於使用objc語言編寫的客戶端:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (application.enabledRemoteNotificationTypes == UIRemoteNotificationTypeNone)
{
[application registerForRemoteNotificationTypes:
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound];
}
application.applicationIconBadgeNumber = -1;
// Override point for customization after application launch.
return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *pushToken = [[[[deviceToken description]
stringByReplacingOccurrencesOfString:@"<"withString:@""]
stringByReplacingOccurrencesOfString:@">" withString:@""]
stringByReplacingOccurrencesOfString: @" " withString: @""];
[[NSUserDefaults standardUserDefaults] setObject:pushToken forKey:@"pushtoken"]; // 保存起來
}
對於使用MonoTouch的客戶端:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
app.RegisterForRemoteNotificationTypes(
UIRemoteNotificationType.Alert |
UIRemoteNotificationType.Badge |
UIRemoteNotificationType.Sound);
app.ApplicationIconBadgeNumber = -1;
// ...
return true;
}
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
// 成功接收到用於消息推送的token
string tokenStr = token.Description;
string pushToken = tokenStr.Replace("<", string.Empty).Replace(">", string.Empty).Replace(" ", string.Empty);
NSUserDefaults.StandardUserDefaults.SetString(pushToken, "pushtoken");
}
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
// 消息推送注冊失敗
}
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
// 接收到推送的消息
// 在iOS7可能需要開啟Background Modes的Remote Notifications
}
在接收到deviceToken的時候先存儲在NSUserDefaults中,在用戶登錄的時候再取出來一起發送到服務端:
NSString *pushToken = [[NSUserDefaults standardUserDefaults] stringForKey:@"pushtoken"]; //objc
string pushToken = NSUserDefaults.StandardUserDefaults.StringForKey("pushtoken"); //MonoTouch
服務端在用戶登錄成功之后,把接收到用戶的用戶名與pushToken關聯起來,在推送消息的時候就可以針對指定用戶來推送,具體的過程略。
而對於不需要用戶登錄的app,可以在接收到deviceToken的時候直接發送到服務端。
更多的客戶端配置參考PushSharp源碼的Client.Samples及PushSharp.Client目錄。
服務端推送消息
var pusher = new PushBroker();
pusher.RegisterAppleService(new ApplePushChannelSettings(File.ReadAllBytes("yourAppId.p12"), "證書的密碼"));
pusher.QueueNotification(
new AppleNotification()
.ForDeviceToken(pushToken) // 從數據庫等地方獲取設備的pushToken
.WithAlert("測試iOS消息推送 - 囧月")
.WithBadge(1)
.WithSound("default")
);
在RegisterAppleService方法中可以注冊多個APNS證書,PushSharp可以自動檢測是Development/Production,這時候需要為證書設置標識:
pusher.RegisterAppleService(new ApplePushChannelSettings(File.ReadAllBytes("yourAppId.p12"), "證書的密碼"), "證書標識如youAppId_development");
pusher.RegisterAppleService(new ApplePushChannelSettings(File.ReadAllBytes("yourAppId.p12"), "證書的密碼"), "證書標識如youAppId_production");
此外,可以注冊各種事件來獲得各種狀態:
pusher.OnDeviceSubscriptionChanged += pusher_OnDeviceSubscriptionChanged;
pusher.OnDeviceSubscriptionExpired += pusher_OnDeviceSubscriptionExpired;
pusher.OnNotificationSent += pusher_OnNotificationSent;
pusher.OnNotificationFailed += pusher_OnNotificationFailed;
pusher.OnNotificationRequeue += pusher_OnNotificationRequeue;
pusher.OnChannelCreated += pusher_OnChannelCreated;
pusher.OnChannelDestroyed += pusher_OnChannelDestroyed;
pusher.OnChannelException += pusher_OnChannelException;
pusher.OnServiceException += pusher_OnServiceException;
static void pusher_OnNotificationFailed(object sender, INotification notification, Exception error)
{
var n = (AppleNotification)notification;
//error.Message ...獲取推送出錯的信息
}
static void pusher_OnNotificationSent(object sender, INotification notification)
{
//消息推送成功后
var n = (AppleNotification)notification;
//n.Payload.Alert.Body 獲取推送的消息內容...
}
static void pusher_OnDeviceSubscriptionExpired(object sender, string expiredSubscriptionId, DateTime expirationDateUtc, INotification notification)
{
// 從數據庫刪除過期的expiredSubscriptionId
}
static void pusher_OnDeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, INotification notification)
{
// 把數據庫中的oldSubscriptionId更新為newSubscriptionId
}
更多請參考源碼的PushSharp.Sample目錄。
參考
官方網站:https://github.com/Redth/PushSharp 可以獲取最新源碼及各種例子
WIKI:https://github.com/Redth/PushSharp/wiki 詳細說明了各平台證書配置的方法
