Forked from jianghaoyuan2007/URL+Extensions.swift
Created
September 27, 2022 07:37
-
-
Save saroar/9d8484c8057fcb409d449082ceaa809f to your computer and use it in GitHub Desktop.
The extensions for URL in Swift.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension URL { | |
/// 返回不带有任何参数的 URL | |
/// let anURLString = "https://127.0.0.1:8080/search/index.html?type=ios&version=1.0" | |
/// let anURL = URL.init(string: anURLString)! | |
/// print(anURL.bareURL) | |
/// Optional(https://127.0.0.1:8080/search/index.html) | |
var bareURL: URL? { | |
var components = URLComponents.init() | |
components.scheme = self.scheme | |
components.host = self.host | |
components.port = self.port | |
components.path = self.path | |
return components.url | |
} | |
/// 返回不带有任何参数的 URL | |
/// let anURLString = "https://127.0.0.1:8080/search/index.html?type=ios&version=1.0" | |
/// let anURL = URL.init(string: anURLString)! | |
/// print(anURL.bareURL) | |
/// Optional(https://127.0.0.1:8080/search/index.html) | |
/// print(anURL.standardURL) | |
/// Optional(https://127.0.0.1:8080/search/index.html?type=ios&version=1.0) | |
var standardURL: URL? { | |
guard let bareURL = self.bareURL else { return nil } | |
guard var components = URLComponents(url: bareURL, resolvingAgainstBaseURL: true) else { return nil } | |
components.query = self.query | |
return components.url | |
} | |
/// 返回该 URL 所包含的参数 | |
/// let anURLString = "https://127.0.0.1:8080/search/index.html?type=ios&version=1.0" | |
/// let anURL = URL.init(string: anURLString)! | |
/// print(anURL.queryItems) | |
/// ["type": "ios", "version": "1.0"] | |
var queryItems: [String: Any] { | |
var items: [String: Any] = [:] | |
guard var components = URLComponents(url: self, resolvingAgainstBaseURL: true) else { return items } | |
guard let queryItems = components.queryItems else { return items } | |
queryItems.forEach { items[$0.name] = $0.value } | |
return items | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment