如何在Swift中设置推送通知

我正在尝试为我的应用程序设置推送通知系统。我有服务器和开发人员许可证来设置推送通知服务。

我目前正在Swift中运行我的应用。我希望能够从服务器远程发送通知。我怎样才能做到这一点?

回答:

尽管可以很好地处理推送通知,但我仍然相信可以立即共享完整的完整案例以简化操作:

要注册APNS的应用程序,(在AppDelegate.swift中的didFinishLaunchingWithOptions方法中包含以下代码)


var settings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes:UIUserNotificationType.Alert|UIUserNotificationType.Sound, categories: nil)

UIApplication.sharedApplication().registerUserNotificationSettings(settings)

UIApplication.sharedApplication().registerForRemoteNotifications()


引入了UserNotifications框架:

导入UserNotifications框架,并在AppDelegate.swift中添加UNUserNotificationCenterDelegate


注册APNS的申请

let center = UNUserNotificationCenter.current()

center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in

// If granted comes true you can enabled features based on authorization.

guard granted else { return }

application.registerForRemoteNotifications()

}

这将调用以下委托方法

func application(application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

//send this device token to server

}

//Called if unable to register for APNS.

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {

println(error)

}

在收到通知后,以下代表将致电:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

println("Recived: \(userInfo)")

//Parsing userinfo:

var temp : NSDictionary = userInfo

if let info = userInfo["aps"] as? Dictionary<String, AnyObject>

{

var alertMsg = info["alert"] as! String

var alert: UIAlertView!

alert = UIAlertView(title: "", message: alertMsg, delegate: nil, cancelButtonTitle: "OK")

alert.show()

}

}

要确定给定的许可,我们可以使用:

UNUserNotificationCenter.current().getNotificationSettings(){ (setttings) in

switch setttings.soundSetting{

case .enabled:

print("enabled sound")

case .disabled:

print("not allowed notifications")

case .notSupported:

print("something went wrong here")

}

}


  • 创建推送通知允许的AppId
  • 使用有效的证书和应用ID创建SSL证书
  • 使用相同的证书创建Provisioning配置文件,并确保在添加沙箱的情况下添加设备(开发Provisioning)

如果在SSL证书后创建配置文件,那会很好。

  • 注册应用程序以进行推送通知
  • 处理didRegisterForRemoteNotificationsWithDeviceToken方法
  • 设置目标>功能>后台模式>远程通知
  • 处理didReceiveRemoteNotification

以上是 如何在Swift中设置推送通知 的全部内容, 来源链接: utcz.com/qa/429202.html

回到顶部