Created
November 23, 2018 05:55
-
-
Save muhlenXi/fa0f281b88372d2486e9c107a8b011ca to your computer and use it in GitHub Desktop.
URL 参数的处理
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 | |
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