如何在Swift中设置推送通知

时间:2014-07-22 22:59:45

标签: ios swift apple-push-notifications

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

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

12 个答案:

答案 0 :(得分:74)

Swift 2:

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

答案 1 :(得分:37)

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

注册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. 使用推送通知
  2. 创建允许的AppId
  3. 使用有效证书和应用ID
  4. 创建SSL证书
  5. 使用相同的证书创建配置文件,并确保在沙盒的情况下添加设备(开发配置) 注意:如果在SSL证书之后创建配置文件,那将是很好的。
  6. 使用代码:

    1. 注册推送通知的应用
    2. 处理didRegisterForRemoteNotificationsWithDeviceToken方法
    3. 设定目标&gt;能力&GT;背景模式&gt;远程通知
    4. 处理didReceiveRemoteNotification

答案 2 :(得分:34)

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

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

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

查看Local and Push Notification Programming Guide

答案 3 :(得分: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();

希望这会对你有所帮助。

答案 4 :(得分: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)
}

答案 5 :(得分:11)

Swift 4

我认为这是正确的iOS 8及以上设置方式。

启用Push Notifications标签中的Capabilities enter image description here

导入UserNotifications

import UserNotifications

修改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
}
  

每次应用启动时调用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)
    }
}
}

退房:Push Notifications Tutorial: Getting Started

答案 6 :(得分: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)
    }

答案 7 :(得分:1)

斯威夫特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

答案 8 :(得分:1)

快捷键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:

}

答案 9 :(得分:0)

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

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
if(UIApplication.sharedApplication().currentUserNotificationSettings() == settings ){
//OK
}else{
//KO
}

答案 10 :(得分:0)

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

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

application.registerUserNotificationSettings(pushSettings)
application.registerForRemoteNotifications()

答案 11 :(得分:0)

100%正常工作... 您可以阅读一个信号文档并正确设置 https://documentation.onesignal.com/docs/ios-sdk-setup 下面的代码将OneSignal导入AppDelegate中

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    OneSignal.setLogLevel(.LL_VERBOSE, visualLevel: .LL_NONE)
    
    // OneSignal initialization
    let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false, kOSSettingsKeyInAppLaunchURL: false]
    
    OneSignal.initWithLaunchOptions(launchOptions,
                                    appId: "YOUR_ONE_SIGNAL_ID",
                                    handleNotificationAction: nil,
                                    settings: onesignalInitSettings)
    
    OneSignal.inFocusDisplayType = OSNotificationDisplayType.inAppAlert;
    // promptForPushNotifications will show the native iOS notification permission prompt.
    // We recommend removing the following code and instead using an In-App Message to prompt for notification permission (See step 8)
    OneSignal.promptForPushNotifications(userResponse: { accepted in
        print("User accepted notifications: \(accepted)")
    })

    return true
}