Skip to content

Instantly share code, notes, and snippets.

@muhlenXi
Created November 23, 2018 05:55
Show Gist options
  • Save muhlenXi/fa0f281b88372d2486e9c107a8b011ca to your computer and use it in GitHub Desktop.
Save muhlenXi/fa0f281b88372d2486e9c107a8b011ca to your computer and use it in GitHub Desktop.
URL 参数的处理
import Foundation
public extension URL {
/// 获取 URL 参数和值
public var queryParameters: [String: String]? {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true), let queryItems = components.queryItems else {
return nil
}
var parameters = [String: String]()
for item in queryItems {
parameters[item.name] = item.value
}
return parameters
}
/// 根据 host 和 queryItems 创建 URL 自动对中文编码处理
public static func createURLWith(host: String, querys: [String: Any]) -> URL? {
let components = NSURLComponents.init(string: host)
var queryItems = [URLQueryItem]()
for (key, value) in querys {
let valueString = "\(value)"
queryItems.append(URLQueryItem.init(name: key, value: valueString))
}
components?.queryItems = queryItems
return components?.url
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment