Ios GCM和swift可以注册并接收成功通知,但不能接收其他推送通知

Ios GCM和swift可以注册并接收成功通知,但不能接收其他推送通知,ios,google-analytics,google-cloud-messaging,apple-push-notifications,Ios,Google Analytics,Google Cloud Messaging,Apple Push Notifications,更新:好的,我重拨了我所有的证书,现在我通过在这个站点测试GCM得到了这个证书 这意味着它基本上被阻止了打电话 更新:好的,所以我一直在努力,并试图改变周围的证书和傻瓜设置。现在,我的控制台正在打印出我已连接到GCM。但是,我仍然没有收到任何来自服务器的通知。这是我的控制台正在打印的内容 0028-05-24 12:21:32.829: GCM | GCM library version 1.1.4 0028-05-24 12:21:32.841: GCM | Invalid key in ch

更新:好的,我重拨了我所有的证书,现在我通过在这个站点测试GCM得到了这个证书

这意味着它基本上被阻止了打电话

更新:好的,所以我一直在努力,并试图改变周围的证书和傻瓜设置。现在,我的控制台正在打印出我已连接到GCM。但是,我仍然没有收到任何来自服务器的通知。这是我的控制台正在打印的内容

0028-05-24 12:21:32.829: GCM | GCM library version 1.1.4
0028-05-24 12:21:32.841: GCM | Invalid key in checkin plist: GMSInstanceIDDeviceDataVersion
2016-05-24 12:21:32.856 MyApp[560:] <GMR/INFO> App measurement v.2003000 started
2016-05-24 12:21:32.857 MuApp[560:] <GMR/INFO> To enable debug logging set the following application argument: -GMRDebugEnabled 
0028-05-24 12:21:32.920: GCM | Invalid key in checkin plist: GMSInstanceIDDeviceDataVersion
2016-05-24 12:21:33.053 MyApp[560:106171] INFO: GoogleAnalytics 3.14 -[GAIReachabilityChecker reachabilityFlagsChanged:] (GAIReachabilityChecker.m:159): Reachability flags update: 0X000002
Registration Token: My token i get from GCM
2016-05-24 12:21:33.067 MyApp[560:] <GMR/INFO> App measurement enabled
Connected to GCM
2016-05-24 12:21:33.937 MyApp[560:106213] INFO: GoogleAnalytics 3.14 -[GAIBatchingDispatcher hitsForDispatch] (GAIBatchingDispatcher.m:368):      No pending hits.
这是我的测试页面,它会收到成功注册的通知:

class PlayGroundController:  UIViewController{



@IBOutlet weak var registeringLabel: UILabel!
@IBOutlet weak var registrationProgressing: UIActivityIndicatorView!

override func viewDidLoad() {
    super.viewDidLoad()
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayGroundController.updateRegistrationStatus(_:)),
                                                     name: appDelegate.registrationKey, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayGroundController.showReceivedMessage(_:)),
                                                     name: appDelegate.messageKey, object: nil)
    registrationProgressing.hidesWhenStopped = true
    registrationProgressing.startAnimating()
}

func updateRegistrationStatus(notification: NSNotification) {
    registrationProgressing.stopAnimating()
    if let info = notification.userInfo as? Dictionary<String,String> {
        if let error = info["error"] {
            registeringLabel.text = "Error registering!"
            showAlert("Error registering with GCM", message: error)
        } else if let _ = info["registrationToken"] {
            registeringLabel.text = "Registered!"
            let message = "Check the xcode debug console for the registration token that you " +
            " can use with the demo server to send notifications to your device"
            showAlert("Registration Successful!", message: message)

        }
    } else {
        print("Software failure. Guru meditation.")
    }
}

func showReceivedMessage(notification: NSNotification) {
    if let info = notification.userInfo as? Dictionary<String,AnyObject> {
        if let aps = info["aps"] as? Dictionary<String, String> {
            showAlert("Message received", message: aps["alert"]!)
        }
    } else {
        print("Software failure. Guru meditation.")
    }
}

func showAlert(title:String, message:String) {

    //Set up for the title color
    let attributedString = NSAttributedString(string: title, attributes: [
        NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here,
        NSForegroundColorAttributeName : UIColor.whiteColor()
        ])
    //Set up for the Message Color
    let attributedString2 = NSAttributedString(string: message, attributes: [
        NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here,
        NSForegroundColorAttributeName : UIColor.whiteColor()
        ])

    let alert = UIAlertController(title: title,message: message, preferredStyle: .Alert)

    alert.setValue(attributedString, forKey: "attributedTitle")
    alert.setValue(attributedString2, forKey: "attributedMessage")
    //alert.view.tintColor = UIColor.whiteColor()
    let dismissAction = UIAlertAction(title: "Dismiss", style: .Destructive, handler: nil)
        alert.addAction(dismissAction)
    self.presentViewController(alert, animated: true, completion: nil)
    //set the color of the Alert
    //let subview = alert.view.subviews.first! as UIView
    //let alertContentView = subview.subviews.first! as UIView
    //alertContentView.backgroundColor = UIColor.blackColor()
    let subview :UIView = alert.view.subviews.last! as UIView
    let alertContentView = subview.subviews.last! as UIView
    alertContentView.backgroundColor = UIColor.blackColor()
    //alertContentView.backgroundColor = UIColor.greenColor()
    //Changes is to a grey color :( 
    /*
    alertContentView.backgroundColor = UIColor(
        red: 0,
        green: 0,
        blue: 0,
        alpha: 1.0)
    //Also another Grey Color Not batman black
    */

    //alertContentView.backgroundColor = UIColor.blueColor()
    //turns into a purple



}

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.LightContent
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}
class PlayGroundController:UIViewController{
@IBOutlet弱var寄存器glabel:UILabel!
@IBOUTLE弱var注册正在进行:UIActivityIndicatorView!
重写func viewDidLoad(){
super.viewDidLoad()
让appDelegate=UIApplication.sharedApplication()。委托为!appDelegate
NSNotificationCenter.defaultCenter().addObserver(self,选择器:#选择器(PlayGroundController.updateRegistrationStatus(:),
名称:appDelegate.registrationKey,对象:nil)
NSNotificationCenter.defaultCenter().addObserver(self,selector:#selector(PlayGroundController.showReceivedMessage(:),
名称:appDelegate.messageKey,对象:nil)
registrationProgressing.hidesWhenStopped=true
注册正在进行中。startAnimating()
}
func updateRegistrationStatus(通知:NSNotification){
注册正在进行。停止设置动画()
如果let info=notification.userInfo as?字典{
如果let error=info[“error”]{
registeringLabel.text=“注册时出错!”
showAlert(“向GCM注册时出错”,消息:错误)
}如果let u=info[“registrationToken”]{
registeringLabel.text=“已注册!”
let message=“检查xcode调试控制台,以获取您需要的注册令牌”+
“可以与演示服务器一起使用向您的设备发送通知”
showAlert(“注册成功!”,消息:消息)
}
}否则{
打印(“软件故障。大师冥想”)
}
}
func showReceivedMessage(通知:NSNotification){
如果let info=notification.userInfo as?字典{
如果让aps=info[“aps”]作为字典{
showAlert(“收到消息”,消息:aps[“警报”!)
}
}否则{
打印(“软件故障。大师冥想”)
}
}
func showAlert(标题:字符串,消息:字符串){
//设置标题颜色
让attributedString=NSAttributedString(字符串:标题,属性:[
NSFontAttributeName:UIFont.systemFontOfSize(15),//此处的字体,
NSForegroundColorAttributeName:UIColor.whiteColor()
])
//设置消息颜色
让attributedString2=NSAttributedString(字符串:消息,属性:[
NSFontAttributeName:UIFont.systemFontOfSize(15),//此处的字体,
NSForegroundColorAttributeName:UIColor.whiteColor()
])
let alert=UIAlertController(标题:标题,消息:消息,首选样式:。警报)
alert.setValue(attributedString,forKey:“attributedTitle”)
alert.setValue(attributedString2,forKey:“attributedMessage”)
//alert.view.tintColor=UIColor.whiteColor()
let dismissAction=UIAlertAction(标题:“dismise”,样式:。破坏性,处理程序:nil)
alert.addAction(dismissAction)
self.presentViewController(警报、动画:true、完成:nil)
//设置警报的颜色
//让subview=alert.view.subviews.first!作为UIView
//让alertContentView=subview.subviews.first!作为UIView
//alertContentView.backgroundColor=UIColor.blackColor()
让子视图:UIView=alert.view.subviews.last!作为UIView
让alertContentView=subview.subviews.last!作为UIView
alertContentView.backgroundColor=UIColor.blackColor()
//alertContentView.backgroundColor=UIColor.greenColor()
//更改为灰色:(
/*
alertContentView.backgroundColor=UIColor(
红色:0,,
绿色:0,
蓝色:0,,
α:1.0)
//还有一种灰色,不是蝙蝠侠黑色
*/
//alertContentView.backgroundColor=UIColor.blueColor()
//变成紫色
}
重写func preferredStatusBarStyle()->UIStatusBarStyle{
返回UIStatusBarStyle.LightContent
}
脱硝{
NSNotificationCenter.defaultCenter().removeObserver(自)
}

当您调用
register
时,您是否从GCM获得注册令牌?如果您有令牌,当您尝试向该令牌发送消息时,服务器会用什么应答?是的,我从register调用中获得令牌。第一个代码块是我的服务器返回的。我正在使用第三方服务器来测试这一点。APN testerIt将为您提供帮助ul允许您包含用于发送消息的请求。您发送下游消息时是否收到成功响应?这是我在我的服务器上使用的。建议测试我的应用程序,因为这样我就不必担心我的服务器也会出现问题。不,我也在运行我的android应用程序Dev Canter中的同一个google项目。这会成为一个问题吗,所以我必须将它们分开?当你调用
register
时,你从GCM获得注册令牌吗?如果你有令牌,当你尝试向该令牌发送消息时,服务器会用什么应答?是的,我从register调用中获得令牌。第一个代码块是我的服务器返回。我正在使用第三方服务器对此进行测试。APN testerIt将有助于您包含用于发送消息的请求。此外,您在发送下游消息时是否收到成功响应?这是我一直在使用的服务器。建议您测试我的应用程序,因为这样我就不会收到响应担心我的父亲
gateway.sandbox.push.apple.com:2195 
2016-05-23 07:56:02 +0000: Connected to server             gateway.sandbox.push.apple.com 
2016-05-23 07:56:02 +0000: Set SSL connection 
2016-05-23 07:56:02 +0000: Set peer domain name gateway.sandbox.push.apple.com 
2016-05-23 07:56:02 +0000: Keychain Opened  
2016-05-23 07:56:02 +0000: Certificate  data  for Apple Development IOS Push Services: com.mywebpage.jp.MyClient initialized successfully 
2016-05-23 07:56:02 +0000: Sec Identity created 
2016-05-23 07:56:02 +0000: Client certificate created 
2016-05-23 07:56:03 +0000: Connected 
2016-05-23 07:56:03 +0000: Token: <0000000c 00000003 00001bff ff1b0000 00001bff ff1b0000 00001bff ff1b0000 00001bff ff1b0000 00001bff 00000e82 000000ef 0000003a 3a000000 0000003a 3a000000 0000003a 3a000000> 
2016-05-23 07:56:03 +0000: Written 92 bytes sending data to gateway.sandbox.push.apple.com:2195 

2016-05-23 07:56:03 +0000: Disconnected from server gateway.sandbox.push.apple.com:2195 
import UIKit
import Foundation

@UIApplicationMain
//add this for GCM
//, GGLInstanceIDDelegate, GCMReceiverDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, GGLInstanceIDDelegate, GCMReceiverDelegate{

let loginInformation = NSUserDefaults.standardUserDefaults()

var window: UIWindow?;

//MARK: Varaibles for GCM
var connectedToGCM = false
var subscribedToTopic = false
var gcmSenderID: String?
var registrationToken: String?
var registrationOptions = [String: AnyObject]()

let registrationKey = "onRegistrationCompleted"
let messageKey = "onMessageReceived"
let subscriptionTopic = "/topics/global"


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    APIManager.sharedInstance.setAuthorization(Config.API_USERNAME, password: Config.API_PASSWORD)

    // [START_EXCLUDE]
    // Configure the Google context: parses the GoogleService-Info.plist, and initializes
    // the services that have entries in the file
    var configureError:NSError?
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")
    gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID
    // [END_EXCLUDE]
    // Register for remote notifications

    let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()


    // [END register_for_remote_notifications]
    // [START start_gcm_service]
    let gcmConfig = GCMConfig.defaultConfig()
    gcmConfig.receiverDelegate = self
    GCMService.sharedInstance().startWithConfig(gcmConfig)
    // [END start_gcm_service]


    //Google Analyitics functions
    // [START tracker_swift]
    // Configure tracker from GoogleService-Info.plist.
    //var configureGAError:NSError?
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")

    // Optional: configure GAI options.
    let gai = GAI.sharedInstance()
    gai.trackUncaughtExceptions = true  // report uncaught exceptions
    gai.logger.logLevel = GAILogLevel.Verbose  // remove before app release
    // [END tracker_swift]



    return true
}


func applicationDidEnterBackground(application: UIApplication) {

    GCMService.sharedInstance().disconnect()
    // [START_EXCLUDE]
    self.connectedToGCM = false
    // [END_EXCLUDE]

}


func applicationDidBecomeActive(application: UIApplication) {

    // Connect to the GCM server to receive non-APNS notifications
    GCMService.sharedInstance().connectWithHandler({(error:NSError?) -> Void in
        if let error = error {
            print("Could not connect to GCM: \(error.localizedDescription)")
        } else {
            self.connectedToGCM = true
            print("Connected to GCM")
        }
    })
}



// [START receive_apns_token]
func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken
    deviceToken: NSData ) {
    // [END receive_apns_token]
    // [START get_gcm_reg_token]
    // 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)
    registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken,
                           kGGLInstanceIDAPNSServerTypeSandboxOption:true]
    GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
                                                             scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
    // [END get_gcm_reg_token]
}



// [START ack_message_reception]
func application( application: UIApplication,
                  didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    print("Notification received: \(userInfo)")
    // This works only if the app started the GCM service
    GCMService.sharedInstance().appDidReceiveMessage(userInfo);
    // Handle the received message
    // [START_EXCLUDE]
    NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
                                                              userInfo: userInfo)
    // [END_EXCLUDE]
}

func application( application: UIApplication,
                  didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                                               fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
    print("Notification received: \(userInfo)")
    // This works only if the app started the GCM service
    GCMService.sharedInstance().appDidReceiveMessage(userInfo);
    // Handle the received message
    // Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
    // [START_EXCLUDE]
    NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
                                                              userInfo: userInfo)
    handler(UIBackgroundFetchResult.NoData);
    // [END_EXCLUDE]
}
// [END ack_message_reception]

func registrationHandler(registrationToken: String!, error: NSError!) {
    if (registrationToken != nil) {
        self.registrationToken = registrationToken
        print("Registration Token: \(registrationToken)")
        //store the registation token for use in the postData function in the login page
        self.loginInformation.setObject(self.registrationToken, forKey: "GCMToken")
        self.loginInformation.synchronize()
        let userInfo = ["registrationToken": registrationToken]
        NSNotificationCenter.defaultCenter().postNotificationName(
            self.registrationKey, object: nil, userInfo: userInfo)
    } else {
        print("Registration to GCM failed with error: \(error.localizedDescription)")
        let userInfo = ["error": error.localizedDescription]
        NSNotificationCenter.defaultCenter().postNotificationName(
            self.registrationKey, object: nil, userInfo: userInfo)
    }
}

// [START on_token_refresh]
func onTokenRefresh() {
    // 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, handler: registrationHandler)
}
// [END on_token_refresh]

// [START upstream_callbacks]
func willSendDataMessageWithID(messageID: String!, error: NSError!) {
    if (error != nil) {
        // Failed to send the message.
    } else {
        // Will send message, you can save the messageID to track the message
    }
}

// [START receive_apns_token_error]
func application( application: UIApplication, didFailToRegisterForRemoteNotificationsWithError
    error: NSError ) {
    print("Registration for remote notification failed with error: \(error.localizedDescription)")
    // [END receive_apns_token_error]
    let userInfo = ["error": error.localizedDescription]
    NSNotificationCenter.defaultCenter().postNotificationName(
        registrationKey, object: nil, userInfo: userInfo)
}


func didSendDataMessageWithID(messageID: String!) {
    // Did successfully send message identified by messageID
}
// [END upstream_callbacks]

func didDeleteMessagesOnServer() {
    // Some messages sent to this device were deleted on the GCM server before reception, likely
    // because the TTL expired. The client should notify the app server of this, so that the app
    // server can resend those messages.
}


//MRAK: End of GCM Function


func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

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 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.
}
}
class PlayGroundController:  UIViewController{



@IBOutlet weak var registeringLabel: UILabel!
@IBOutlet weak var registrationProgressing: UIActivityIndicatorView!

override func viewDidLoad() {
    super.viewDidLoad()
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayGroundController.updateRegistrationStatus(_:)),
                                                     name: appDelegate.registrationKey, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayGroundController.showReceivedMessage(_:)),
                                                     name: appDelegate.messageKey, object: nil)
    registrationProgressing.hidesWhenStopped = true
    registrationProgressing.startAnimating()
}

func updateRegistrationStatus(notification: NSNotification) {
    registrationProgressing.stopAnimating()
    if let info = notification.userInfo as? Dictionary<String,String> {
        if let error = info["error"] {
            registeringLabel.text = "Error registering!"
            showAlert("Error registering with GCM", message: error)
        } else if let _ = info["registrationToken"] {
            registeringLabel.text = "Registered!"
            let message = "Check the xcode debug console for the registration token that you " +
            " can use with the demo server to send notifications to your device"
            showAlert("Registration Successful!", message: message)

        }
    } else {
        print("Software failure. Guru meditation.")
    }
}

func showReceivedMessage(notification: NSNotification) {
    if let info = notification.userInfo as? Dictionary<String,AnyObject> {
        if let aps = info["aps"] as? Dictionary<String, String> {
            showAlert("Message received", message: aps["alert"]!)
        }
    } else {
        print("Software failure. Guru meditation.")
    }
}

func showAlert(title:String, message:String) {

    //Set up for the title color
    let attributedString = NSAttributedString(string: title, attributes: [
        NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here,
        NSForegroundColorAttributeName : UIColor.whiteColor()
        ])
    //Set up for the Message Color
    let attributedString2 = NSAttributedString(string: message, attributes: [
        NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here,
        NSForegroundColorAttributeName : UIColor.whiteColor()
        ])

    let alert = UIAlertController(title: title,message: message, preferredStyle: .Alert)

    alert.setValue(attributedString, forKey: "attributedTitle")
    alert.setValue(attributedString2, forKey: "attributedMessage")
    //alert.view.tintColor = UIColor.whiteColor()
    let dismissAction = UIAlertAction(title: "Dismiss", style: .Destructive, handler: nil)
        alert.addAction(dismissAction)
    self.presentViewController(alert, animated: true, completion: nil)
    //set the color of the Alert
    //let subview = alert.view.subviews.first! as UIView
    //let alertContentView = subview.subviews.first! as UIView
    //alertContentView.backgroundColor = UIColor.blackColor()
    let subview :UIView = alert.view.subviews.last! as UIView
    let alertContentView = subview.subviews.last! as UIView
    alertContentView.backgroundColor = UIColor.blackColor()
    //alertContentView.backgroundColor = UIColor.greenColor()
    //Changes is to a grey color :( 
    /*
    alertContentView.backgroundColor = UIColor(
        red: 0,
        green: 0,
        blue: 0,
        alpha: 1.0)
    //Also another Grey Color Not batman black
    */

    //alertContentView.backgroundColor = UIColor.blueColor()
    //turns into a purple



}

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.LightContent
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}