Zee
Zee

Reputation: 25

Universal Link opens app but fails to save user_id in UserDefaults

I'm using Universal Links in my iOS app, and the link correctly opens the app as expected. However, I'm having trouble saving the user_id parameter from the URL to UserDefaults. Here’s my setup:

import UIKit

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
              let incomingURL = userActivity.webpageURL else {
            return false
        }

        // Check for "open" in path and get the "user_id" query parameter
        if incomingURL.pathComponents.contains("open"),
           let userID = incomingURL.queryParameters?["user_id"] {
            
            // Attempt to save userID to UserDefaults
            UserDefaults.standard.set(userID, forKey: "user_id")
            return true
        }

        return false
    }
}

URLExtensions.swift

import Foundation

extension URL {
    var queryParameters: [String: String]? {
        var params = [String: String]()
        let queryItems = URLComponents(url: self, resolvingAgainstBaseURL: false)?.queryItems
        queryItems?.forEach {
            params[$0.name] = $0.value
        }
        return params
    }
}

How i call the user id

import SwiftUI

struct ContentView: View {
    @State private var userId: String = ""  // State for user_id to display it in the UI

    var body: some View {
        VStack {
            Text("User ID: \(userId.isEmpty ? "Not Available" : userId)")
                .foregroundColor(.white)
                .padding()

            Button("Check User ID") {
                // For testing, manually fetch and display UserDefaults value
                userId = getUserId()
                print("Fetched User ID:", userId)
            }
        }
        .onAppear {
            // Fetch user_id when the view appears
            userId = getUserId()
            print("User ID on appear:", userId)
        }
        .background(Color.gray)
    }

    func getUserId() -> String {
        // Retrieves user_id from UserDefaults
        return UserDefaults.standard.string(forKey: "user_id") ?? ""
    }
}

The link looks like this: https://example.com/open?user_id=a4a64be8-9a74-4960-8f0b-80aee292614f

The app opens correctly with the Universal Link, but the user_id is not saved to UserDefaults as expected.

I've verified the URL structure and that the user_id parameter exists in the link. However, when retrieving UserDefaults.standard.string(forKey: "user_id") later, it’s returning nil.

Am I missing something in my code that’s preventing user_id from being saved?

Upvotes: 0

Views: 119

Answers (1)

duckSern1108
duckSern1108

Reputation: 1115

  1. You should verify that you are using @UIApplicationDelegateAdaptor in your app in order to have method in AppDelegate called
  2. You should use @AppStorage property wrapper instead get UserDefaults's data in onAppear closure: Change from @State private var userId: String = "" to @AppStorage("user_id") private var userId: String = ""

Upvotes: 0

Related Questions