Skip to content

Instantly share code, notes, and snippets.

@gkye
Last active September 6, 2020 16:48
Show Gist options
  • Save gkye/4ce8a99d78fa68a0b6608346fc60db2e to your computer and use it in GitHub Desktop.
Save gkye/4ce8a99d78fa68a0b6608346fc60db2e 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)
}
}
}
@mahbodtaba
Copy link

Hi thanks for tutorial. please help me I have very emergency error
I am very new in swift I create application and I make server with java and I have IP valid for http but my question is how can I get request for my parametes(ProvidedEmailAddress,,,userPassword,,,,userRepeatPassword) which line of your code I can write my parameters and how can I use it????

@freemansion
Copy link

swift 4 update for String extension:

func stringByAddingPercentEncodingForURLQueryValue() -> String? {
        let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
        return self.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment