Skip to content

Instantly share code, notes, and snippets.

@morengab
Forked from armstrongnate/basic-auth.swift
Last active April 7, 2020 08:12
Show Gist options
  • Save morengab/8e8782af5fb9d9ec5acd to your computer and use it in GitHub Desktop.
Save morengab/8e8782af5fb9d9ec5acd to your computer and use it in GitHub Desktop.
HTTP POST Request with Basic Authentication using NSURLSession in Swift
// Other sources: http://swiftdeveloperblog.com/send-http-post-request-example-using-swift-and-php/
// Create request
let baseUrl = "http://www.ocrwebservice.com/restservices/processDocument",
params = "?language=english&gettext=true&outputformat=txt",
requestUrl = NSURL(string: "\(baseUrl)\(params)"),
request = NSMutableURLRequest(URL:requestUrl!)
request.HTTPMethod = "POST";
request.HTTPBodyStream = NSInputStream(fileAtPath: "[/YOUR/FILE/PATH/IMAGE.jpg]")
// Create session configuration (for authentication)
let config = NSURLSessionConfiguration.defaultSessionConfiguration(),
userPasswordString = "[USERNAME]:[PASSWORD]",
userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding),
base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(nil),
authString = "Basic \(base64EncodedCredential)"
config.HTTPAdditionalHeaders = ["Authorization" : authString]
// Create session
let session = NSURLSession(configuration: config)
// Set up task for execution
let task = session.dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("response = \(response)")
println("dataString = \(dataString)")
//Convert response sent from a server side script to a NSDictionary object:
var err: NSError?
var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary
if let parseJSON = myJSON {
// Now we can access values of the data object by their keys
var availPages = parseJSON["AvailablePages"] as? Int
var OCRText = (parseJSON["OCRText"] as? NSArray)
println("Available Pages: \(availPages!)")
println("OCRText: \(OCRText!)")
}
}
task.resume()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment