将url参数添加到swift中每个url的末尾

时间:2017-03-30 18:29:36

标签: ios swift uiwebview url-parameters

我使用下面的代码在webview中显示我的网站?app = ios参数到网址的末尾。但现在我希望在网站上的所有网址中添加此参数。我需要在加载每个页面之前将其附加到某处。请指导我,因为我是一个快速的新手。感谢

include("db_conx.php"); //Connect to db mysqli
$sql = "SELECT MAX(id) as id FROM tbl_uploads";  
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];

的AppDelegate

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)

注意:我在网站上检查了与此相关的几乎所有主题,但无法找到满足我需求的答案。

1 个答案:

答案 0 :(得分:2)

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")])!);
}