0

I am testing in Swift to send notifications with Firebase and in general it's working. When i will send a notification to one user, i need the device token of this user. I guess this is not the same as the UUID? By the creation of the account i like to store this id in the db by adding the id in the url (GET) in the webview page. How can i do that? Is there a solution?

Here's the ViewController.swift code

import UIKit import WebKit class ViewController: UIViewController { let webView=WKWebView() override func viewDidLoad() { super.viewDidLoad() view.addSubview(webView) guard let url = URL(string: "**https://myurl.be/app.php?device=CODE**")else { return } webView.load(URLRequest(url:url)) // Do any additional setup after loading the view. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() webView.frame = view.bounds } } 

AppDelegate.swift

 import UIKit import FirebaseCore import FirebaseMessaging import UserNotifications @main class AppDelegate: UIResponder, UIApplicationDelegate { let gcmMessageIDKey = "gcm.Message_ID" var deviceTokenString: String? var testString = "test" func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}) print("===== deviceTokenString =====") print(deviceTokenString ?? "nok") } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() // Push Notifications if #available(iOS 10.0, *) { UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: { _, _ in } ) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() Messaging.messaging().delegate = self return true } func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) } } extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo print(userInfo) completionHandler([[.alert, .sound]]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo print(userInfo) completionHandler() } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { if let messageID = userInfo[gcmMessageIDKey] { print("Message ID: \(messageID)") } print(userInfo) completionHandler(UIBackgroundFetchResult.newData) } } extension AppDelegate: MessagingDelegate { func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { print("Firebase registration token: \(String(describing: fcmToken))") let dataDict: [String: String] = ["token": fcmToken ?? ""] NotificationCenter.default.post( name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict ) } func application(_application:UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){ print (deviceToken.map({String(format: "%02x", $0 )}).joined()) //optie1 print (deviceToken.reduce(""){ $0 + String (format: "%02.2hhx", $1)}) //optie2 print (deviceToken.reduce(""){ $0 + String (format: "%.2x", $1)}) //optie3 } } 

I hope to find a solution.

2 Answers 2

0

I am not 100% sure, if I understand your problem correctly but..

When it comes to storing the deviceToken, according to Apple's documentation, you might want to send it to your server every time you call the UIApplication.registerUserNotificationSettings(_:) method.

And it is a good idea because, as they say:

Important Never cache device tokens in local storage. APNs issues a new token when the user restores a device from a backup, when the user installs your app on a new device, and when the user reinstalls the operating system. You get an up-to-date token each time you ask the system to provide the token.

You can do it here:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { self.sendDeviceTokenToServer(data: deviceToken) } 
Sign up to request clarification or add additional context in comments.

5 Comments

Thankl you for the quick response... English is not my first language...
When i add self.sendDeviceTokenToServer(data: deviceToken)
it gives an error Value of type 'AppDelegate' has no member 'sendDeviceTokenToServer'
How do i get the deviceToken in the URL in my viewColtroller?
sendDeviceTokenToServer(data:) is not an existing method. It is only a placeholder for a method you can implement yourself. It would involve some kind of networking service you also need to implement on your own.
-1

Output breakpoint I can see the token in the AppDelegate file:

output breakpoint I can see the token in the AppDelegate file

import UIKit import WebKit class ViewController: UIViewController{ let webView=WKWebView() override func viewDidLoad() { super.viewDidLoad() view.addSubview(webView) let deviceTokenString="nok" //FILL IN SOMETHING /* NOT WORKING THIS IS WHERE I WANT TO HAVE THE TOKEN guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } guard let deviceTokenString = appDelegate.deviceTokenString else { // deviceTokenString isn't available return } // deviceTokenString is available here */ let deviceid = UIDevice.current.identifierForVendor!.uuidString guard let url = URL(string: "https://mysite.be/app.php?os=ios&dt=\(deviceid)&token=\(deviceTokenString)")else { return } webView.load(URLRequest(url:url)) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() webView.frame = view.bounds } } 

1 Comment

Is this an answer to your question or is this more information about your question? If this is the solution then please update the answer to explain what was wrong and how this fixes the issue. If this is more information, then please delete this "answer" and edit your original question as needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.