Skip to content

Instantly share code, notes, and snippets.

@HomerJSimpson
Created October 19, 2015 21:25
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save HomerJSimpson/80c95f0424b8e9718a40 to your computer and use it in GitHub Desktop.
Save HomerJSimpson/80c95f0424b8e9718a40 to your computer and use it in GitHub Desktop.
POST application/x-www-form-urlencoded via swift
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely(true)
extension NSMutableURLRequest {
/// Percent escape
///
/// Percent escape in conformance with W3C HTML spec:
///
/// See http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
///
/// - parameter string: The string to be percent escaped.
/// - returns: Returns percent-escaped string.
private func percentEscapeString(string: String) -> String {
let characterSet = NSCharacterSet.alphanumericCharacterSet().mutableCopy() as! NSMutableCharacterSet
characterSet.addCharactersInString("-._* ")
return string
.stringByAddingPercentEncodingWithAllowedCharacters(characterSet)!
.stringByReplacingOccurrencesOfString(" ", withString: "+", options: [], range: nil)
}
/// Encode the parameters for `application/x-www-form-urlencoded` request
///
/// - parameter parameters: A dictionary of string values to be encoded in POST request
func encodeParameters(parameters: [String : String]) {
HTTPMethod = "POST"
let parameterArray = parameters.map { (key, value) -> String in
return "\(key)=\(self.percentEscapeString(value))"
}
HTTPBody = parameterArray.joinWithSeparator("&").dataUsingEncoding(NSUTF8StringEncoding)
}
}
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = [
"Accept" : "application/json",
"Content-Type" : "application/x-www-form-urlencoded"
]
let session = NSURLSession(configuration: config)
let request = NSMutableURLRequest(URL: NSURL(string:"https://XXXXX.com/mobile-helper.jsp")!)
request.encodeParameters(["name" : "user.name@not.local", "passwd":"Passwd123"])
let task = session.dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else {
print(error)
return
}
print(JSON(data:data!))
}
task.resume()
@theMoe
Copy link

theMoe commented Jan 13, 2018

What do I have to change to use it with Swift 4?

@drhr
Copy link

drhr commented Mar 19, 2018

@theMoe minor changes are needed:

extension URLRequest {
  
  private func percentEscapeString(_ string: String) -> String {
    var characterSet = CharacterSet.alphanumerics
    characterSet.insert(charactersIn: "-._* ")
    
    return string
      .addingPercentEncoding(withAllowedCharacters: characterSet)!
      .replacingOccurrences(of: " ", with: "+")
      .replacingOccurrences(of: " ", with: "+", options: [], range: nil)
  }
  
  mutating func encodeParameters(parameters: [String : String]) {
    httpMethod = "POST"
    
    let parameterArray = parameters.map { (arg) -> String in
      let (key, value) = arg
      return "\(key)=\(self.percentEscapeString(value))"
    }
    
    httpBody = parameterArray.joined(separator: "&").data(using: String.Encoding.utf8)
  }
}

let url = URL(string: "<YOUR URL HERE>")
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
  "Accept" : "application/json",
  "Content-Type" : "application/x-www-form-urlencoded"
]

let session = URLSession(configuration: config)

var request = URLRequest(url: url!)
request.encodeParameters(parameters: ["username": username, "password": password])

let task = session.dataTask(with: request) { data, response, error in
  guard error == nil && data != nil else {
      print(error)
      return
  }
  print(JSON(data:data!))
}
task.resume()

@edw
Copy link

edw commented Apr 18, 2018

This is super-useful code. Would you mind explicitly placing it under an MIT, BSD, LGPL, or similar license?

@janeshsutharios
Copy link

@edw You are right ! what a workaround 👍 )

@rahul-inspired-iosdeveloper

@drhr

Thanks for the answer

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