我在我的iOS应用程序中使用AFNetworking,并且对于它所做的所有GET请求,我从基本URL构建url,然后使用NSDictionary键值对添加参数.
问题是我需要相同的键来表示不同的值.
以下是我需要最终URL的示例 -
http://example.com/.....&id=21212&id=21212&id=33232
NSDictionary中不可能在相同的键中具有不同的值.所以我尝试了NSSet但是没有用.
let productIDSet: Set = [prodIDArray] let paramDict = NSMutableDictionary() paramDict.setObject(productIDSet, forKey: "id")
有人可以帮忙吗?
你需要的只是NSURLComponents
.基本思想是为你的id创建一堆查询项.这是您可以粘贴到游乐场的代码:
import UIKit import XCPlayground let queryItems = [NSURLQueryItem(name: "id", value: "2121"), NSURLQueryItem(name: "id", value: "3232")] let urlComps = NSURLComponents(string: "www.apple.com/help")! urlComps.queryItems = queryItems let URL = urlComps.URL! XCPlaygroundPage.currentPage.captureValue(URL.absoluteString, withIdentifier: "URL")
你应该看到一个输出
www.apple.com/help?id=2121&id=3232
它可以将QueryItem添加到现有URL.
extension URL { func appending(_ queryItem: String, value: String?) -> URL { guard var urlComponents = URLComponents(string: absoluteString) else { return absoluteURL } // Create array of existing query items var queryItems: [URLQueryItem] = urlComponents.queryItems ?? [] // Create query item let queryItem = URLQueryItem(name: queryItem, value: value) // Append the new query item in the existing query items array queryItems.append(queryItem) // Append updated query items array in the url component object urlComponents.queryItems = queryItems // Returns the url from new url components return urlComponents.url! } }
如何使用
var url = URL(string: "https://www.example.com")! let finalURL = url.appending("test", value: "123") .appending("test2", value: nil)
func queryString(_ value: String, params: [String: String]) -> String? { var components = URLComponents(string: value) components?.queryItems = params.map { element in URLQueryItem(name: element.key, value: element.value) } return components?.url?.absoluteString }