面试题答案
一键面试实现步骤
- 配置App以处理URL:在
AppDelegate
或SceneDelegate
(iOS 13+)中配置应用来处理传入的URL。 - 解析URL参数:从URL中提取所需的参数,如商品ID。
- 验证参数合法性:检查参数是否符合预期格式,例如商品ID是否为有效的数字。
- 更新视图状态:将解析并验证后的参数传递给相关视图,更新视图状态以显示特定商品详情。
安全机制
- 输入验证:严格验证传入参数的格式和范围,防止恶意数据注入。
- 数据过滤:避免直接使用未经过滤的参数执行数据库查询等操作,防止SQL注入等攻击。
- URL Scheme注册:使用唯一且不易被猜到的URL Scheme,防止其他应用恶意调用。
代码示例
- 配置App处理URL(iOS 13+,SceneDelegate.swift)
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let url = URLContexts.first?.url else { return }
if let components = URLComponents(url: url, resolvingAgainstBaseURL: true),
let itemIdString = components.queryItems?.first(where: { $0.name == "itemId" })?.value,
let itemId = Int(itemIdString) {
// 验证商品ID为有效数字
let contentView = ContentView(itemId: itemId)
let hostingController = UIHostingController(rootView: contentView)
window?.rootViewController = hostingController
}
}
}
- ContentView.swift
import SwiftUI
struct ContentView: View {
let itemId: Int
var body: some View {
Text("Displaying details for item with ID: \(itemId)")
}
}
- 注册URL Scheme:在
Info.plist
文件中添加以下内容:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>yourappscheme</string>
</array>
</dict>
</array>
这样,当用户通过yourappscheme://?itemId=123
这样的URL打开应用时,应用会解析并验证itemId
,然后更新视图显示相应商品详情。