Как настроить push-уведомления в Swift
Я пытаюсь настроить систему push-уведомлений для своего приложения. У меня есть сервер и лицензия разработчика для настройки службы push-уведомлений.
В настоящее время я запускаю свое приложение в Swift. Я хотел бы иметь возможность отправлять уведомления удаленно с моего сервера. Как я могу это сделать?
Ответы
Ответ 1
Несмотря на то, что ответ дается для обработки push-уведомлений, я все же полагаю, что сразу расскажу об интегрированном законченном случае:
Чтобы зарегистрировать приложение для APNS, (включите следующий код в метод didFinishLaunchingWithOptions внутри AppDelegate.swift)
IOS 9
var settings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes:UIUserNotificationType.Alert|UIUserNotificationType.Sound, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
После IOS 10
Введен фреймворк UserNotifications:
Импортируйте структуру UserNotifications и добавьте UNUserNotificationCenterDelegate в AppDelegate.swift.
Зарегистрировать заявку на 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:
- Создание AppId разрешено с Push-уведомлением
- Создать сертификат SSL с действительным сертификатом и идентификатором приложения
- Создайте профиль Provisioning с тем же сертификатом и обязательно добавьте устройство в случае изолированной среды (подготовка к разработке). Примечание. Это будет хорошо, если создать профиль Provisioning после SSL-сертификата.
С кодом:
- Зарегистрируйте приложение для push-уведомлений
- Обрабатывать метод didRegisterForRemoteNotificationsWithDeviceToken
- Установите цели> Возможности> фоновые режимы> Удаленное уведомление
- Обрабатывать didReceiveRemoteNotification
Ответ 2
Swift 2:
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
Ответ 3
Чтобы зарегистрироваться для получения push-уведомлений через Apple Push Service, вы должны вызвать метод registerForRemoteNotifications()
UIApplication
.
Если регистрация завершается успешно, приложение вызывает ваш объект делегата object application:didRegisterForRemoteNotificationsWithDeviceToken:
и передает ему токен устройства.
Вы должны передать этот токен вместе с сервером, который вы используете для создания push-уведомлений для устройства. Если регистрация завершается неудачно, приложение вместо этого вызывает его делегат application:didFailToRegisterForRemoteNotificationsWithError:
.
Посмотрите Руководство по программированию локальных и Push Notification.
Ответ 4
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();
Надеюсь, это поможет вам.
Ответ 5
Чтобы поддерживать 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)
}
Ответ 6
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 wasnt 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-уведомлениям: начало работы
Ответ 7
Спасибо за более ранние ответы. Xcode внесла некоторые изменения, и вот код SWIFT 2, который проходит проверку кода XCode 7 и поддерживает как iOS 7, так и выше:
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
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()
Обязательно импортируйте UserNotifications в верхней части вашего контроллера представления.
import UserNotifications
Ответ 9
Swift 4
Импортируйте структуру UserNotifications и добавьте UNUserNotificationCenterDelegate в AppDelegate.
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate
Чтобы зарегистрировать приложение для APNS, (включите следующий код в метод didFinishLaunchingWithOptions внутри AppDelegate.swift)
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:
}
Ответ 10
Вы можете отправить уведомление, используя следующий фрагмент кода:
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
if(UIApplication.sharedApplication().currentUserNotificationSettings() == settings ){
//OK
}else{
//KO
}
Ответ 11
Я использую этот снимок кода в AppDelegate.swift:
let pushType = UIUserNotificationType.alert.union(.badge).union(.sound)
let pushSettings = UIUserNotificationSettings(types: pushType
, categories: nil)
application.registerUserNotificationSettings(pushSettings)
application.registerForRemoteNotifications()