通用链接打开应用程序,但无法将 user_id 保存到 UserDefaults 中

问题描述 投票:0回答:1

我在 iOS 应用程序中使用通用链接,并且该链接可以按预期正确打开应用程序。但是,我在将 URL 中的 user_id 参数保存到 UserDefaults 时遇到问题。这是我的设置:

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

我如何调用用户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") ?? ""
    }
}

链接如下所示:

https://example.com/open?user_id=a4a64be8-9a74-4960-8f0b-80aee292614f

应用程序可以使用通用链接正确打开,但

user_id
未按预期保存到
UserDefaults

我已验证 URL 结构以及链接中存在

user_id
参数。但是,稍后检索
UserDefaults.standard.string(forKey: "user_id")
时,它会返回
nil

我的代码中是否遗漏了某些内容,导致 user_id 无法保存?

ios swift swiftui ios-universal-links
1个回答
0
投票
  1. 您应该验证您正在应用程序中使用
    @UIApplicationDelegateAdaptor
    ,以便在
    AppDelegate
    中调用方法
  2. 您应该使用
    @AppStorage
    属性包装器,而不是在
    onAppear
    闭包中获取 UserDefaults 的数据: 从
    @State private var userId: String = ""
    更改为
    @AppStorage("user_id") private var userId: String = ""
© www.soinside.com 2019 - 2024. All rights reserved.