Skip to content

Instantly share code, notes, and snippets.

@Ilesh
Forked from gkye/getRequest.swift
Created September 6, 2020 16:48
Show Gist options
  • Save Ilesh/e5a684ea2b9a023e64e926d0d86001a9 to your computer and use it in GitHub Desktop.
Save Ilesh/e5a684ea2b9a023e64e926d0d86001a9 to your computer and use it in GitHub Desktop.
NSURLSession: GET Request with parameters swift 2.0
//Encode params to be web friendly and return a string. Reference ->http://stackoverflow.com/a/27724627/6091482
extension String {
/// Percent escapes values to be added to a URL query as specified in RFC 3986
///
/// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Returns percent-escaped string.
func stringByAddingPercentEncodingForURLQueryValue() -> String? {
let allowedCharacters = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
return self.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters)
}
}
extension Dictionary {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// This percent escapes in compliance with RFC 3986
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
let parameterArray = self.map { (key, value) -> String in
let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (value as! String).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return parameterArray.joinWithSeparator("&")
}
}
//Request
class HTTPRequest{
class func request(url: String, parameters: [String: AnyObject],completionHandler: (data: NSData?, response: NSURLResponse?, error: NSError?) -> ()) -> (){
let parameterString = parameters.stringFromHttpParameters()
let url = NSURL(string: "\(url)?\(parameterString)")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error -> \(error)")
completionHandler(data: nil, response: nil, error: error)
}else{
completionHandler(data: data, response: response, error: nil)
}
}
task.resume()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let params = [
"APIKEY": "API_KEY",
"ANOTHERPARAM": "ANOTHERONE"
]
HTTPRequest.request("URLHERE", parameters: params){
rtn in
if(rtn.error == nil){
do {
let result = try NSJSONSerialization.JSONObjectWithData(rtn.data!, options: []) as? [String:AnyObject]
print("Result -> \(result)")
} catch {
print("Error -> \(error)")
}
}else{
print(rtn.error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment