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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is super-useful code. Would you mind explicitly placing it under an MIT, BSD, LGPL, or similar license?