ios-如何在Swi中设置推送通知

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

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

BlakeH asked 2020-02-22T20:29:14Z
11个解决方案
74 votes

斯威夫特2:

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
Adam Waite answered 2020-02-22T20:31:03Z
39 votes

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

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

iOS 9

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

在IOS 10之后

引入了UserNotifications框架:

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

注册APNS申请

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
}
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")
        }
    }

因此,APNS的清单:

  1. 创建推送通知允许的AppId
  2. 使用有效的证书和应用ID创建SSL证书
  3. 使用相同的证书创建配置文件,并确保在添加沙箱的情况下添加设备(开发配置)注意:如果在SSL证书后创建配置文件,那会很好。

使用代码:

  1. 注册应用程序以进行推送通知
  2. 处理didRegisterForRemoteNotificationsWithDeviceToken方法
  3. 设置目标>功能>后台模式>远程通知
  4. 处理didReceiveRemoteNotification
Arvind answered 2020-02-22T20:30:43Z
34 votes

要注册通过Apple Push Service接收推送通知,您必须调用application:didFailToRegisterForRemoteNotificationsWithError:registerForRemoteNotifications()方法。

如果注册成功,则应用程序将调用您的应用程序委托对象的application:didFailToRegisterForRemoteNotificationsWithError:方法,并将该方法传递给设备令牌。

您应该将此令牌传递到用于为设备生成推送通知的服务器。 如果注册失败,则该应用将调用其应用代表的application:didFailToRegisterForRemoteNotificationsWithError:方法。

查看“本地和推送通知编程指南”。

RaffAl answered 2020-02-22T20:31:37Z
26 votes

UIUserNotification已从ios8中删除。

所以你应该使用UIUserNotification

代码示例:

var type = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound;
var setting = UIUserNotificationSettings(forTypes: type, categories: nil);
UIApplication.sharedApplication().registerUserNotificationSettings(setting);
UIApplication.sharedApplication().registerForRemoteNotifications();

希望这会帮助你。

Dog Su answered 2020-02-22T20:32:10Z
15 votes

要支持ios 8及更低版本,请使用以下命令:

// Register for Push Notitications, if running iOS 8
if application.respondsToSelector("registerUserNotificationSettings:") {

  let types:UIUserNotificationType = (.Alert | .Badge | .Sound)
  let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)

  application.registerUserNotificationSettings(settings)
  application.registerForRemoteNotifications()

} else {      
  // Register for Push Notifications before iOS 8
  application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound)
}
Gmeister4 answered 2020-02-22T20:32:30Z
11 votes

斯威夫特4

我认为这是在iOS 8及更高版本中进行设置的正确方法。

application(_:didRegisterUserNotificationSettings:)标签中打开AppDelegateenter image description here

进口AppDelegate

import UserNotifications

修改AppDelegate

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


    if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {

        // If your app wasn’t running and the user launches it by tapping the push notification, the push notification is passed to your app in the launchOptions

        let aps = notification["aps"] as! [String: AnyObject]
        UIApplication.shared.applicationIconBadgeNumber = 0
    }

    registerForPushNotifications()

    return true
}

每次启动应用程序时都要致电AppDelegate,这一点非常重要。 这是因为用户可以随时进入“设置”应用并更改通知权限。 application(_:didRegisterUserNotificationSettings:)将始终为您提供用户当前为您的应用所允许的权限。

复制粘贴此AppDelegate扩展名

// Push Notificaion
extension AppDelegate {
func registerForPushNotifications() {
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
            [weak self] (granted, error) in
            print("Permission granted: \(granted)")

            guard granted else {
                print("Please enable \"Notifications\" from App Settings.")
                self?.showPermissionAlert()
                return
            }

            self?.getNotificationSettings()
        }
    } else {
        let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(settings)
        UIApplication.shared.registerForRemoteNotifications()
    }
}

@available(iOS 10.0, *)
func getNotificationSettings() {

    UNUserNotificationCenter.current().getNotificationSettings { (settings) in
        print("Notification settings: \(settings)")
        guard settings.authorizationStatus == .authorized else { return }
        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let tokenParts = deviceToken.map { data -> String in
        return String(format: "%02.2hhx", data)
    }

    let token = tokenParts.joined()
    print("Device Token: \(token)")
    //UserDefaults.standard.set(token, forKey: DEVICE_TOKEN)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register: \(error)")
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

    // If your app was running and in the foreground
    // Or
    // If your app was running or suspended in the background and the user brings it to the foreground by tapping the push notification

    print("didReceiveRemoteNotification /(userInfo)")

    guard let dict = userInfo["aps"]  as? [String: Any], let msg = dict ["alert"] as? String else {
        print("Notification Parsing Error")
        return
    }
}

func showPermissionAlert() {
    let alert = UIAlertController(title: "WARNING", message: "Please enable access to Notifications in the Settings app.", preferredStyle: .alert)

    let settingsAction = UIAlertAction(title: "Settings", style: .default) {[weak self] (alertAction) in
        self?.gotoAppSettings()
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)

    alert.addAction(settingsAction)
    alert.addAction(cancelAction)

    DispatchQueue.main.async {
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)
    }
}

private func gotoAppSettings() {

    guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
        return
    }

    if UIApplication.shared.canOpenURL(settingsUrl) {
        UIApplication.shared.openURL(settingsUrl)
    }
}
}

检出:推送通知教程:入门

Warif Akhand Rishi answered 2020-02-22T20:33:21Z
8 votes

感谢您的早期答案。 Xcode进行了一些更改,这是通过XCode 7代码检查并支持iOS 7及更高版本的SWIFT 2代码:

    if #available(iOS 8.0, *) {
        let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)
        UIApplication.sharedApplication().registerForRemoteNotifications()
    } else {
        let settings = UIRemoteNotificationType.Alert.union(UIRemoteNotificationType.Badge).union(UIRemoteNotificationType.Sound)
        UIApplication.sharedApplication().registerForRemoteNotificationTypes(settings)
    }
Oliver Zhang answered 2020-02-22T20:33:41Z
2 votes

斯威夫特4

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

import UserNotifications

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate

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

let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
    }
    application.registerForRemoteNotifications()

这将调用以下委托方法

func application(_ application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    //send this device token to server

}

//Called if unable to register for APNS.
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print(error)
}

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

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

    print("Recived: \(userInfo)")
    //Parsing userinfo:

}
jojo answered 2020-02-22T20:34:19Z
1 votes

斯威夫特3:

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
    }
UIApplication.shared.registerForRemoteNotifications()

确保在视图控制器顶部导入UserNotifications。

import UserNotifications
Henry answered 2020-02-22T20:34:43Z
0 votes

您可以使用以下代码段发送通知:

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
if(UIApplication.sharedApplication().currentUserNotificationSettings() == settings ){
//OK
}else{
//KO
}
Pierre-Yves Guillemet answered 2020-02-22T20:35:03Z
0 votes

我在AppDelegate.swift中使用以下代码片段:

let pushType = UIUserNotificationType.alert.union(.badge).union(.sound)
let pushSettings = UIUserNotificationSettings(types: pushType
            , categories: nil)

application.registerUserNotificationSettings(pushSettings)
application.registerForRemoteNotifications()
ZYiOS answered 2020-02-22T20:35:23Z
translate from https://stackoverflow.com:/questions/24899257/how-to-set-up-push-notifications-in-swift