gpt4 book ai didi

ios - 快速将url参数添加到每个url的末尾

转载 作者:行者123 更新时间:2023-11-28 12:26:56 27 4
gpt4 key购买 nike

我正在使用下面的代码在 webview 中显示我的网站,并将 ?app=ios 参数添加到 url 的末尾。但是现在我想在网站上的所有url中添加这个参数。我需要在加载每个页面之前将其附加到某处。请指导我解决这个问题,因为我是 swift 的新手。谢谢

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

@IBOutlet var container: UIView!

var webView: WKWebView!

override func viewDidLoad() {
super.viewDidLoad()

webView = WKWebView()
container.addSubview(webView)

self.webView.navigationDelegate = self
self.webView.uiDelegate = self
}

let urlStr = "https://www.website.com/?app=ios"
let url = NSURL(string: urlStr)!
let req = NSURLRequest(url: url as URL)

webView.load(req as URLRequest)

应用委托(delegate)

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}

注意:我已经检查了网站上几乎所有与此相关的主题,但找不到满足我需要的答案。

最佳答案

NSURLComponents是一个非常方便的类,用于解析和更改 URL。

这应该做你想做的:

import Cocoa

func addQueryParams(url: URL, newParams: [URLQueryItem]) -> URL? {
let urlComponents = NSURLComponents.init(url: url, resolvingAgainstBaseURL: false)
guard urlComponents != nil else { return nil; }
if (urlComponents?.queryItems == nil) {
urlComponents!.queryItems = [];
}
urlComponents!.queryItems!.append(contentsOf: newParams);
return urlComponents?.url;
}

let url = URL.init(string: "https://developer.apple.com/documentation/foundation/nsurlcomponents/1416476-init");
if (url != nil) {
print(addQueryParams(url: url!, newParams: [URLQueryItem.init(name: "a", value: "b")])!);
}

关于ios - 快速将url参数添加到每个url的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43125736/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com