我对 swift 很陌生,所以我的代码中可能会有很多错误,但我想要实现的是使用参数向本地主机服务器发送
GET
请求。更重要的是,鉴于我的函数采用两个参数baseURL:string,params:NSDictionary
,我正在尝试实现它。我不确定如何将这两者结合到实际的 URLRequest 中?这是我到目前为止所尝试过的
func sendRequest(url:String,params:NSDictionary){
let urls: NSURL! = NSURL(string:url)
var request = NSMutableURLRequest(URL:urls)
request.HTTPMethod = "GET"
var data:NSData! = NSKeyedArchiver.archivedDataWithRootObject(params)
request.HTTPBody = data
println(request)
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request, completionHandler:loadedData)
task.resume()
}
}
func loadedData(data:NSData!,response:NSURLResponse!,err:NSError!){
if(err != nil){
println(err?.description)
}else{
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println(jsonResult)
}
}
构建
GET
请求时,请求没有正文,而是一切都在 URL 上。要构建 URL(以及正确的转义百分比),您还可以使用 URLComponents
。
var url = URLComponents(string: "https://www.google.com/search/")!
url.queryItems = [
URLQueryItem(name: "q", value: "War & Peace")
]
唯一的技巧是大多数 Web 服务需要
+
字符百分比转义(因为它们会将其解释为 application/x-www-form-urlencoded
规范规定的空格字符)。但 URLComponents
无法逃脱它。 Apple 认为 +
是查询中的有效字符,因此不应被转义。从技术上讲,它们是正确的,它在 URI 查询中是允许的,但它在 application/x-www-form-urlencoded
请求中具有特殊含义,实际上不应该以未转义的方式传递。
Apple 承认我们必须对
+
字符进行百分比转义,但建议我们手动执行此操作:
var url = URLComponents(string: "https://www.wolframalpha.com/input/")!
url.queryItems = [
URLQueryItem(name: "i", value: "1+2")
]
url.percentEncodedQuery = url.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
这是一个不太优雅的解决方法,但它确实有效,并且如果您的查询可能包含
+
字符并且您有一个将它们解释为空格的服务器,Apple 建议您这样做。
因此,将其与您的
sendRequest
例程结合起来,您最终会得到如下结果:
func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
var components = URLComponents(string: url)!
components.queryItems = parameters.map { (key, value) in
URLQueryItem(name: key, value: value)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let request = URLRequest(url: components.url!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard
let data = data, // is there data
let response = response as? HTTPURLResponse, // is there HTTP response
200 ..< 300 ~= response.statusCode, // is statusCode 2XX
error == nil // was there no error
else {
completion(nil, error)
return
}
let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
completion(responseObject, nil)
}
task.resume()
}
你会这样称呼它:
sendRequest("someurl", parameters: ["foo": "bar"]) { responseObject, error in
guard let responseObject = responseObject, error == nil else {
print(error ?? "Unknown error")
return
}
// use `responseObject` here
}
就个人而言,我现在会使用
JSONDecoder
并返回自定义 struct
而不是字典,但这在这里并不真正相关。希望这说明了如何将参数百分比编码到 GET 请求的 URL 中的基本思想。
请参阅 此答案的先前修订版,了解 Swift 2 和手动百分比转义演绎版。
使用 NSURLComponents 构建你的 NSURL 像这样
var urlComponents = NSURLComponents(string: "https://www.google.de/maps/")!
urlComponents.queryItems = [
NSURLQueryItem(name: "q", value: String(51.500833)+","+String(-0.141944)),
NSURLQueryItem(name: "z", value: String(6))
]
urlComponents.URL // returns https://www.google.de/maps/?q=51.500833,-0.141944&z=6
来源:https://www.ralfebert.de/snippets/ios/encoding-nsurl-get-parameters/
我正在使用这个,在操场上尝试一下。在 Constants 中将基本 url 定义为 Struct
struct Constants {
struct APIDetails {
static let APIScheme = "https"
static let APIHost = "restcountries.eu"
static let APIPath = "/rest/v1/alpha/"
}
}
private func createURLFromParameters(parameters: [String:Any], pathparam: String?) -> URL {
var components = URLComponents()
components.scheme = Constants.APIDetails.APIScheme
components.host = Constants.APIDetails.APIHost
components.path = Constants.APIDetails.APIPath
if let paramPath = pathparam {
components.path = Constants.APIDetails.APIPath + "\(paramPath)"
}
if !parameters.isEmpty {
components.queryItems = [URLQueryItem]()
for (key, value) in parameters {
let queryItem = URLQueryItem(name: key, value: "\(value)")
components.queryItems!.append(queryItem)
}
}
return components.url!
}
let url = createURLFromParameters(parameters: ["fullText" : "true"], pathparam: "IN")
//Result url= https://restcountries.eu/rest/v1/alpha/IN?fullText=true
斯威夫特3:
extension URL {
func getQueryItemValueForKey(key: String) -> String? {
guard let components = NSURLComponents(url: self, resolvingAgainstBaseURL: false) else {
return nil
}
guard let queryItems = components.queryItems else { return nil }
return queryItems.filter {
$0.name.lowercased() == key.lowercased()
}.first?.value
}
}
我用它来获取
UIImagePickerController
中func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
的图像名称:
var originalFilename = ""
if let url = info[UIImagePickerControllerReferenceURL] as? URL, let imageIdentifier = url.getQueryItemValueForKey(key: "id") {
originalFilename = imageIdentifier + ".png"
print("file name : \(originalFilename)")
}
如果键和值都符合
Dictionary
,您可以扩展stringFromHttpParameter
,仅提供CustomStringConvertable
,如下所示
extension Dictionary where Key : CustomStringConvertible, Value : CustomStringConvertible {
func stringFromHttpParameters() -> String {
var parametersString = ""
for (key, value) in self {
parametersString += key.description + "=" + value.description + "&"
}
return parametersString
}
}
这更干净,可以防止在没有业务调用该方法的字典上意外调用
stringFromHttpParameters
@Rob 建议的这个扩展适用于 Swift 3.0.1
我无法使用 Xcode 8.1 (8B62) 编译他在帖子中包含的版本
extension Dictionary {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
var parametersString = ""
for (key, value) in self {
if let key = key as? String,
let value = value as? String {
parametersString = parametersString + key + "=" + value + "&"
}
}
parametersString = parametersString.substring(to: parametersString.index(before: parametersString.endIndex))
return parametersString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
}
func relationsApi(_ search: String) {
let url = URL(string: getApiUrl)!
let session = URLSession.shared
let queryItems = [URLQueryItem(name: "search", value: search)]
var urlComps = URLComponents(string: getApiUrl)!
urlComps.queryItems = queryItems
let result = urlComps.url!
print(result)
var request = URLRequest(url: result)
request.setValue( "Bearer \(tokenName)", forHTTPHeaderField: "Authorization")
let task = session.dataTask(with: request) { (data, response, error) in
if let error = error{
print (error)
} else if let data = data {
do {
let decoder = JSONDecoder()
let responseDatas = try decoder.decode(RelationsAPIModel.self, from: data)
// print(responseDatas)
DispatchQueue.main.async {
self.namesArr = responseDatas.data.relation
// self.subname = responseDatas.data.relation[Re]
self.relationTableView.reloadData()
}
} catch {
print(error)
}
} else {
print("something went wrong")
}
}
task.resume()
}
}
我用:
let dictionary = ["method":"login_user",
"cel":mobile.text!
"password":password.text!] as Dictionary<String,String>
for (key, value) in dictionary {
data=data+"&"+key+"="+value
}
request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding);