ios 带参数的Swift GET请求

oyxsuwqo  于 2022-12-15  发布在  iOS
关注(0)|答案(7)|浏览(154)

我对swift还很陌生,所以我的代码中可能会有很多错误,但我想实现的是用参数向localhost服务器发送一个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)

    }

}
edqdpe6u

edqdpe6u1#

当构建一个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不会对其进行百分比转义。苹果认为+是查询中的有效字符,因此不应进行转义。从技术上讲,他们是正确的,在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中的基本思想。
请参阅previous revision of this answer了解Swift 2和手动百分比转义格式副本。

o2rvlv0m

o2rvlv0m2#

使用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/

hvvq6cgz

hvvq6cgz3#

我正在用这个,在操场上试试。定义基本网址为常量结构

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
nvbavucw

nvbavucw4#

雨燕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
    }
}

我用它来获取func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])UIImagePickerController的映像名称:

var originalFilename = ""
if let url = info[UIImagePickerControllerReferenceURL] as? URL, let imageIdentifier = url.getQueryItemValueForKey(key: "id") {
    originalFilename = imageIdentifier + ".png"
    print("file name : \(originalFilename)")
}
bjg7j2ky

bjg7j2ky5#

如果键和值都符合CustomStringConvertable,则可以扩展Dictionary以仅提供stringFromHttpParameter,如下所示

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方法的字典上意外调用该方法

um6iljoc

um6iljoc6#

@Rob建议的这个扩展适用于Swift 3.0.1
我无法用Xcode 8.1(8B 62)编译他帖子中包含的版本

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)!
    }

}
lpwwtiir

lpwwtiir7#

我用途:

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);

相关问题