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() }
Option B: Firebase Dynamic Links (Better for Fallbacks)
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() } }
Step 2: Configure Your App to Accept Deep Links
For Custom URL Scheme
Add a URL scheme to your Info.plist:
- Open your
Info.plistas source code (right-click > Open As > Source Code) - 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>
For Firebase Dynamic Links
- In Xcode, go to your target’s Signing & Capabilities tab
- Add the Associated Domains capability
- Add a domain in the format
applinks:yourapp.page.link(replace with your Dynamic Links domain)
Step 3: Handle Deep Links in Your App
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=test123under Edit Scheme > Run > Arguments).
内容的提问来源于stack exchange,提问作者Collin Stewart

