Como configurar as notificações push no Swift

Estou a tentar configurar um sistema de notificação de push para a minha aplicação. Eu tenho um servidor e uma licença de desenvolvedor para configurar o serviço de notificação push.

Estou a correr a minha aplicação no Swift. Gostaria de poder enviar as notificações remotamente do meu servidor. Como posso fazer isto?

Author: RaffAl, 2014-07-23

10 answers

Embora a resposta seja bem dada para lidar com a notificação de push, ainda assim acredito em partilhar o caso completo integrado de uma vez para facilitar:

Registar a aplicação para APNS, (incluir o seguinte código no didfinishlaunching com o método de options dentro do AppDelegate.swift)

IOS 9

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

Após IOS 10

Introduziu o quadro das notificações de Utilização:

Importar o quadro de notificações de Utilizador e adicionar o servidor de intoxicação não utilizado em AppDelegate.swift

Para registar o pedido de APNS

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

Isto irá requerer o seguinte método de delegado

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)

}

Ao receber a notificação, o seguinte delegado chamará:

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()
            }
}

Para identificar a permissão dada podemos usar:

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")
        }
    }

A lista de controlo dos APNS:

  1. é permitido criar o AppId com a notificação Push
  2. criar um certificado SSL com o certificado válido e o ID da aplicação
  3. Criar um perfil de Provisionamento com o mesmo certificado e certifique-se de adicionar dispositivo em caso de sandboxing(provisionamento de desenvolvimento) Nota: isso será bom se criar um perfil de provisionamento após o certificado SSL.

Com Código:

  1. registe a app para a notificação push
  2. manipular didregister forremotenotificationswithdevicetoken method
  3. Definir objectivos> capacidade> modos de fundo> Notificação à distância
  4. manipular didReceiveRemoteNotification
 33
Author: Arvind, 2018-03-14 10:01:59

Swift 2:

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
 74
Author: Adam Waite, 2015-06-27 21:20:01

Para se registar para receber notificações de push através do serviço de Push da Apple, tem de chamar um método registerForRemoteNotifications() de UIApplication.

Se o registo for bem-sucedido, o aplicativo chama o método do seu objeto delegado app application:didRegisterForRemoteNotificationsWithDeviceToken: e passa-o como um dispositivo.

Deve passar este item para o servidor que usa para gerar notificações de push para o dispositivo. Se o registo falhar,o aplicativo chama o método application:didFailToRegisterForRemoteNotificationsWithError: do seu delegado app.

Dê uma vista de olhos em Local e pressione a notificação Guia De Programação .

 34
Author: RaffAl, 2017-02-13 22:27:35

registerForRemoteNotification() foi retirado do ios8.

UIUserNotification

EXEMPLO DE CÓDIGO:

var type = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound;
var setting = UIUserNotificationSettings(forTypes: type, categories: nil);
UIApplication.sharedApplication().registerUserNotificationSettings(setting);
UIApplication.sharedApplication().registerForRemoteNotifications();
Espero que isto te ajude.
 25
Author: Dog Su, 2015-12-08 01:50:20

Para suportar OS ios 8 e antes, use isto:

// 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)
}
 15
Author: Gmeister4, 2015-02-26 12:23:46

Swift 4

Acho que este é o caminho correcto para a configuração em iOS 8 e acima.

Liga Push Notifications na página Capabilities enter image description here

Importação UserNotifications

import UserNotifications

Modificar 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
}
É extremamente importante ligar sempre que a aplicação é lançada. Isto porque o usuário pode, a qualquer momento, ir para o aplicativo de configuração e alterar as permissões de notificação. application(_:didRegisterUserNotificationSettings:) dar-lhe-á sempre as permissões do utilizador atualmente permitiu a sua aplicação.

Copiar colar esta AppDelegate extensão

// 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)
    }
}
}

Verificar: enviar notificações Tutorial: A Iniciar

 9
Author: Warif Akhand Rishi, 2018-04-23 07:01:48
Obrigado pelas respostas anteriores. Xcode fez algumas alterações e aqui está o código SWIFT 2 que passa Xcode 7 verificação de código e suporta tanto iOS 7 e acima:
    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)
    }
 8
Author: Oliver Zhang, 2015-12-23 10:26:37

Swift 3:

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

Certifique-se de importar as utilidades no topo do seu controlador de visualização.

import UserNotifications
 1
Author: Henry, 2017-07-12 17:13:17

Pode enviar a notificação usando o seguinte excerto de código:

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
if(UIApplication.sharedApplication().currentUserNotificationSettings() == settings ){
//OK
}else{
//KO
}
 0
Author: Pierre-Yves Guillemet, 2015-09-27 20:10:17

Uso este código snip em AppDelegate.swift:

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

application.registerUserNotificationSettings(pushSettings)
application.registerForRemoteNotifications()
 0
Author: ZYiOS, 2017-11-21 08:47:07