Swift万能动态路由URL模式
万能动态路由(URL 模式)是一个在 Swift 中实用的导航和通信工具,能让你的应用变得更加灵活。通过自定义URL Scheme
,你可以像调用链接一样,轻松地在应用内做导航,打开视图控制器、调用服务或者执行特定功能。这种方式比较简洁而且效率高,适用于复杂的应用场景。
比如,你可以这样设置一个 URL:
let urlComponents = URLComponents(string: "myapp://viewcontroller")!
urlComponents.queryItems = [
URLQueryItem(name: "id", value: "123"),
URLQueryItem(name: "name", value: "John")
]
let url = urlComponents.url!
这样创建的 URL,包含了参数,可以方便地传递数据。,你可以在AppDelegate.swift
中的application(_:continue:restorationHandler:)
方法里这些 URL,快速响应用户的操作:
func application(_ app: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
let url = userActivity.webpageURL else { return false }
let queryItems = url.queryItems! // 解析并 queryItems...
return true
}
此外,像如果你还没用过这种方式,强烈推荐试试,适合那些需要灵活、高效管理导航和通信的大型应用。
26.8KB
文件大小:
评论区