Created
October 19, 2015 21:25
-
-
Save HomerJSimpson/80c95f0424b8e9718a40 to your computer and use it in GitHub Desktop.
POST application/x-www-form-urlencoded via swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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" : "[email protected]", "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 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()
This is super-useful code. Would you mind explicitly placing it under an MIT, BSD, LGPL, or similar license?
@edw You are right ! what a workaround 👍 )
Thanks for the answer
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What do I have to change to use it with Swift 4?