我正在尝试使用GCM从php发送推送通知。 Receiver是一款iOS设备。我没有收到来自iOS设备的通知,但如果我尝试使用PostMan,我就会收到它。我在php API中取得了成功 -
{" multicast_id":6620946920649682270,"成功":1,"失效":0," canonical_ids":0,&# 34;结果":[{" MESSAGE_ID":" 0:1452841688393271%bcdb604df9fd7ecd"}]}
我在php写的内容
<?php
// Your API key
$api_key = "sgvdahgsvasbjbsKqaFHap4PC745ezKBS47Xs0QZV8";
// Client IDs from your application
$registration_ids = array( "lojInK-jPug:APA91bFnmo81ue- GRdByVZVn_QSY8jpTHJnsdasdkasdkRwRnJ9gE4fQtfI_VfxfGSuCFhQIriem84HI9nTWEqXfRblHz_YkqHOMnzjBgvPRp8pRWeDm3fVO9a5w3MtsMUf" );
$message = "hello, test!!";
// URL to POST to
$gcm_url = 'https://android.googleapis.com/gcm/send';
// data to be posted
$fields = array(
'registration_ids' => $registration_ids,
'data' => array( "message" => '"notification" :{"sound":"default","badge":"2","body":"Test Push!"}' ),
);
// headers for the request
$headers = array(
'Authorization: key=' . $api_key,
'Content-Type: application/json'
);
$curl_handle = curl_init();
// set CURL options
curl_setopt( $curl_handle, CURLOPT_URL, $gcm_url );
curl_setopt( $curl_handle, CURLOPT_POST, true );
curl_setopt( $curl_handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $curl_handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl_handle, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// send
echo $response = curl_exec($curl_handle);
curl_close($curl_handle);
// let's check the response
$data = json_decode($response);
foreach ($data['results'] as $key => $value) {
if ($value['registration_id']) {
printf("%s has a new registration id: %s\r\n", $key, $value['registration_id']);
}
if ($value['error']) {
printf("%s encountered error: %s\r\n", $key, $value['error']);
}
if ($value['message_id']) {
printf("%s was successfully sent, message id: %s", $key, $value['message_id']);
}
}
?>
在iOS中我尝试过 -
@UIApplicationMain
class AppDelegate: UIResponder,UIApplicationDelegate,AsyncDataProviderDelegate,GGLInstanceIDDelegate {
var window: UIWindow?
var successToken = ""
var launchOpt : NSDictionary?
var rootControllerVC : UIViewController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:.Normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(red: 10.00/255.00, green: 32.00/255.00, blue: 32.00/255.00, alpha: 1)], forState:.Selected)
let tabFont = UIFont(name:"Helvetica-Bold", size: 12)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: tabFont!], forState:.Normal)
if #available(iOS 8.0, *)
{
let types:UIUserNotificationType = ([.Alert, .Sound, .Badge])
let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else
{
application.registerForRemoteNotificationTypes([.Alert, .Sound, .Badge])
}
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
NetworkManager.sharedInstance.delegate = self
// Override point for customization after application launch.
return true
}
func callRegisterAPi(regId : String)
{
let detailDict = NSMutableDictionary()
detailDict.setObject(kDeviceType, forKey:deviceType)
detailDict.setObject(kDeviceId, forKey:deviceId)
detailDict.setObject(regId, forKey: registerID)
detailDict.setObject(kguiVersion, forKey:guiVersion)
NetworkManager.sharedInstance.registerDeviceApi("POST", isAsynchronous: true, userDictionary: detailDict)
}
//MARK:- AsyncData Provider delgate
func dataGivenBack(resultDataDict: NSMutableDictionary, methodName: String) {
if successToken != ""
{
NSUserDefaults.standardUserDefaults().setObject(successToken, forKey:kToken)
}
}
//MARK:- Push Notification Delegate Methods
func application(application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
let characterSet: NSCharacterSet = NSCharacterSet( charactersInString: "<>" )
let deviceTokenString: String = ( deviceToken.description as NSString ).stringByTrimmingCharactersInSet( characterSet ).stringByReplacingOccurrencesOfString( " ",withString: "" ) as String
print("token is \(deviceTokenString)")
// Create a config and set a delegate that implements the GGLInstaceIDDelegate protocol.
let instanceIDConfig = GGLInstanceIDConfig.defaultConfig()
instanceIDConfig.delegate = self
// Start the GGLInstanceID shared instance with that config and request a registration
// token to enable reception of notifications
GGLInstanceID.sharedInstance().startWithConfig(instanceIDConfig)
let registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:true]
let gcmSenderID = "83985659474"
GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
}
func registrationHandler(registrationToken: String!, error: NSError!) {
if (registrationToken != nil) {
successToken = registrationToken
print("GCM Token is :\(registrationToken)")
if isDeviceTokenChanged(registrationToken)
{
callRegisterAPi(registrationToken)
}
print("Registred")
} else {
print("Registration to GCM failed with error: \(error.localizedDescription)")
}
}
func onTokenRefresh() {
let registrationOptions = [kGGLInstanceIDRegisterAPNSOption:successToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:true]
let gcmSenderID = "83985659474"
// A rotation of the registration tokens is happening, so the app needs to request a new token.
print("The GCM registration token needs to be changed.")
GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
scope: kGGLInstanceIDScopeGCM, options: registrationOptions as [NSObject : AnyObject], handler: registrationHandler)
}
//Called if unable to register for APNS.
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError)
{
print("not registered to APNS,\(error)")
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
{
GCMService.sharedInstance().appDidReceiveMessage(userInfo);
print("Receiving dict is :\(userInfo)")
rootControllerVC = mainStoryBoard.instantiateViewControllerWithIdentifier("startingPage") as UIViewController
self.window?.rootViewController = rootControllerVC
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
completionHandler(UIBackgroundFetchResult.NewData)
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
GCMService.sharedInstance().connectWithHandler({
(NSError error) -> Void in
if error != nil {
print("Could not connect to GCM: \(error.localizedDescription)")
} else
{
//self.connectedToGCM = true
print("Connected to GCM")
// ...
}
})
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}