You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4中基于Firebase实现扫码跳转指定用户资料的技术咨询

Hey there! Let's fix this step by step—your current QR code points directly to a Firebase database URL, which will open in a browser instead of your app. We need to set up deep linking (either custom URL schemes or Firebase Dynamic Links) to launch your app and pass the user's UID, then load their profile data.


Step 1: Update Your QR Code Content

Instead of using the Firebase database URL, generate a link that will trigger your app. You have two solid options:

Option A: Custom URL Scheme (Simple, Quick Setup)

Use a custom scheme like myapp:// to directly open your app. Modify your QR string generation code:

override func viewDidLoad() {
    super.viewDidLoad()
    guard let uid = Auth.auth().currentUser?.uid else { 
        // Handle case where user isn't logged in
        return 
    }
    // Custom deep link with UID as a parameter
    let qrString = "myapp://userProfile?uid=\(uid)"
    let data = qrString.data(using: .isoLatin1, allowLossyConversion: false)
    
    // Rest of your QR code generation code remains the same
    let filter = CIFilter(name: "CIQRCodeGenerator")
    filter!.setValue(data, forKey: "inputMessage")
    filter!.setValue("Q", forKey: "inputCorrectionLevel")
    qrcodeImage = filter?.outputImage
    displayQRCodeImage()
}

Dynamic Links are ideal if you want to handle users who don’t have your app installed (they’ll be sent to the App Store or a web page). First, set up Firebase Dynamic Links in your project, then generate the link like this:

import FirebaseDynamicLinks

override func viewDidLoad() {
    super.viewDidLoad()
    guard let uid = Auth.auth().currentUser?.uid else { return }
    
    // Base link that points to your app's profile flow
    let baseLink = URL(string: "https://yourapp.page.link/userProfile?uid=\(uid)")!
    let domainPrefix = "https://yourapp.page.link" // Replace with your Dynamic Links domain
    
    let linkBuilder = DynamicLinkComponents(link: baseLink, domainURIPrefix: domainPrefix)
    // Configure iOS app settings
    linkBuilder.iOSParameters = DynamicLinkIOSParameters(bundleID: "com.yourcompany.yourapp") // Replace with your bundle ID
    linkBuilder.iOSParameters?.appStoreID = "123456789" // Optional: Your App Store ID
    
    // Generate the final dynamic link URL
    if let dynamicLinkURL = linkBuilder.url() {
        let qrString = dynamicLinkURL.absoluteString
        // Use this qrString to generate your QR code (same as before)
        let data = qrString.data(using: .isoLatin1, allowLossyConversion: false)
        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter!.setValue(data, forKey: "inputMessage")
        filter!.setValue("Q", forKey: "inputCorrectionLevel")
        qrcodeImage = filter?.outputImage
        displayQRCodeImage()
    }
}

For Custom URL Scheme

Add a URL scheme to your Info.plist:

  1. Open your Info.plist as source code (right-click > Open As > Source Code)
  2. Add this code inside the <dict> tag:
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>myapp</string> <!-- Match the scheme in your QR link -->
        </array>
    </dict>
</array>
  1. In Xcode, go to your target’s Signing & Capabilities tab
  2. Add the Associated Domains capability
  3. Add a domain in the format applinks:yourapp.page.link (replace with your Dynamic Links domain)

You need to catch the incoming link, extract the UID, and navigate to the user profile page.

For iOS 12 and Earlier (AppDelegate)

Add this to your AppDelegate.swift:

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    handleDeepLink(url: url)
    return true
}

private func handleDeepLink(url: URL) {
    guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
          let uid = components.queryItems?.first(where: { $0.name == "uid" })?.value else {
        return
    }
    
    // Navigate to the user profile view controller
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let profileVC = storyboard.instantiateViewController(withIdentifier: "UserProfileViewController") as? UserProfileViewController else { return }
    
    profileVC.targetUserUID = uid // Pass the UID to the profile VC
    if let navController = window?.rootViewController as? UINavigationController {
        navController.pushViewController(profileVC, animated: true)
    } else {
        window?.rootViewController = UINavigationController(rootViewController: profileVC)
    }
}

For iOS 13+ (SceneDelegate)

Add this to your SceneDelegate.swift:

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let url = URLContexts.first?.url else { return }
    handleDeepLink(url: url)
}

private func handleDeepLink(url: URL) {
    // Same handleDeepLink code as above
    guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
          let uid = components.queryItems?.first(where: { $0.name == "uid" })?.value else {
        return
    }
    
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let profileVC = storyboard.instantiateViewController(withIdentifier: "UserProfileViewController") as? UserProfileViewController else { return }
    
    profileVC.targetUserUID = uid
    if let windowScene = scene as? UIWindowScene,
       let navController = windowScene.windows.first?.rootViewController as? UINavigationController {
        navController.pushViewController(profileVC, animated: true)
    }
}

Step 4: Load the Target User’s Data in the Profile Page

In your UserProfileViewController, add a property to hold the target UID, then fetch the data from Firebase:

import FirebaseDatabase

class UserProfileViewController: UIViewController {
    var targetUserUID: String?
    @IBOutlet weak var usernameLabel: UILabel!
    // Add other UI elements for profile data
    
    override func viewDidLoad() {
        super.viewDidLoad()
        guard let uid = targetUserUID else { return }
        
        // Fetch user profile from Firebase Realtime Database
        let userRef = Database.database().reference().child("userProfile").child(uid)
        userRef.observeSingleEvent(of: .value) { snapshot in
            guard let userData = snapshot.value as? [String: Any] else { return }
            // Update UI with user data
            self.usernameLabel.text = userData["username"] as? String
            // Load avatar, bio, etc., similarly
        }
    }
}

Important Notes

  • Firebase Security Rules: Make sure your database rules allow other users to read profile data. For example:
    {
      "rules": {
        "userProfile": {
          "$uid": {
            ".read": true, // Or restrict to authenticated users: "auth != null"
            ".write": "$uid === auth.uid"
          }
        }
      }
    }
    
  • Testing Deep Links: You can test by entering your custom link in Safari (e.g., myapp://userProfile?uid=test123) or using Xcode’s scheme arguments (add -url myapp://userProfile?uid=test123 under Edit Scheme > Run > Arguments).

内容的提问来源于stack exchange,提问作者Collin Stewart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:54:19