如何在Swift中设置推送通知

Bla*_*keH 48 apple-push-notifications ios swift

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

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

Ada*_*ite 74

斯威夫特2:

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
Run Code Online (Sandbox Code Playgroud)


Arv*_*ind 41

虽然答案很好地处理推送通知,但我仍然相信立即分享集成的完整案例以便:

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

IOS 9

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

在IOS 10之后

推出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()
}
Run Code Online (Sandbox Code Playgroud)

这将调用以下委托方法

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)

}
Run Code Online (Sandbox Code Playgroud)

在委托后接收通知将致电:

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()
            }
}
Run Code Online (Sandbox Code Playgroud)

要确定我们可以使用的权限:

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")
        }
    }
Run Code Online (Sandbox Code Playgroud)

所以APNS清单:

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

使用代码:

  1. 注册推送通知的应用程序
  2. 处理didRegisterForRemoteNotificationsWithDeviceToken方法
  3. 设置目标>功能>后台模式>远程通知
  4. 处理didReceiveRemoteNotification


Raf*_*fAl 34

要注册以通过Apple Push Service接收推送通知,您必须调用registerForRemoteNotifications()方法UIApplication.

如果注册成功,应用程序将调用您的app delegate对象的application:didRegisterForRemoteNotificationsWithDeviceToken:方法并将其传递给设备令牌.

您应该将此令牌传递给用于为设备生成推送通知的服务器.如果注册失败,应用程序将调用其app delegate的application:didFailToRegisterForRemoteNotificationsWithError:方法.

查看本地和推送通知编程指南.

  • 记得在目标设置 - >功能中切换**ON**"推送通知". (3认同)
  • `registerForRemoteNotifications()`仅适用于`iOS 8`,我们应该为`iOS 7`使用什么? (2认同)

小智 26

registerForRemoteNotification() 已从ios8中删除.

所以你应该使用 UIUserNotification

代码示例:

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

希望这会帮助你.


Gme*_*er4 15

要支持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)
}
Run Code Online (Sandbox Code Playgroud)


War*_*shi 11

斯威夫特4

我认为这是在设置正确的方法iOS 8和上面.

Push NotificationsCapabilities选项卡中 打开在此输入图像描述

进口 UserNotifications

import UserNotifications
Run Code Online (Sandbox Code Playgroud)

修改 didFinishLaunchingWithOptions

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
}
Run Code Online (Sandbox Code Playgroud)

registerUserNotificationSettings(_:)每次启动应用程序时调用都非常重要.这是因为用户可以随时进入"设置"应用并更改通知权限.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)
    }
}
}
Run Code Online (Sandbox Code Playgroud)

退房:推送通知教程:入门


Oli*_*ang 8

谢谢你早先的答案.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)
    }
Run Code Online (Sandbox Code Playgroud)