I am utilizing Common Hyperlinks in my iOS app, and the hyperlink accurately opens the app as anticipated. Nonetheless, I am having hassle saving the user_id parameter from the URL to UserDefaults. Right here’s my setup:
import UIKit
class AppDelegate: UIResponder, UIApplicationDelegate {
func utility(_ utility: UIApplication, proceed userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
let incomingURL = userActivity.webpageURL else {
return false
}
// Test for "open" in path and get the "user_id" question parameter
if incomingURL.pathComponents.accommodates("open"),
let userID = incomingURL.queryParameters?["user_id"] {
// Try to save lots of userID to UserDefaults
UserDefaults.normal.set(userID, forKey: "user_id")
return true
}
return false
}
}
URLExtensions.swift
import Basis
extension URL {
var queryParameters: [String: String]? {
var params = [String: String]()
let queryItems = URLComponents(url: self, resolvingAgainstBaseURL: false)?.queryItems
queryItems?.forEach {
params[$0.name] = $0.worth
}
return params
}
}
How i name the consumer id
import SwiftUI
struct ContentView: View {
@State non-public var userId: String = "" // State for user_id to show it within the UI
var physique: some View {
VStack {
Textual content("Consumer ID: (userId.isEmpty ? "Not Out there" : userId)")
.foregroundColor(.white)
.padding()
Button("Test Consumer ID") {
// For testing, manually fetch and show UserDefaults worth
userId = getUserId()
print("Fetched Consumer ID:", userId)
}
}
.onAppear {
// Fetch user_id when the view seems
userId = getUserId()
print("Consumer ID on seem:", userId)
}
.background(Shade.grey)
}
func getUserId() -> String {
// Retrieves user_id from UserDefaults
return UserDefaults.normal.string(forKey: "user_id") ?? ""
}
}
The hyperlink seems to be like this: https://instance.com/open?user_id=a4a64be8-9a74-4960-8f0b-80aee292614f
The app opens accurately with the Common Hyperlink, however the user_id
just isn’t saved to UserDefaults
as anticipated.
I’ve verified the URL construction and that the user_id
parameter exists within the hyperlink. Nonetheless, when retrieving UserDefaults.normal.string(forKey: "user_id")
later, it’s returning nil
.
Am I lacking one thing in my code that’s stopping user_id from being saved?