Credential request not working in swift - ios

I ported some objective-c code (with some changes) to swift and the link w/o "private" in it works and the other doesn't. Here"s what I have:
import Cocoa
class MasterViewController: NSViewController, NSURLSessionDataDelegate {
var session: NSURLSession!
var courses: JSON!
override func viewDidLoad() {
super.viewDidLoad()
let config: NSURLSessionConfiguration? =
NSURLSessionConfiguration.defaultSessionConfiguration()
session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil )
fetchFeed()
}
func fetchFeed() {
let requestString: String = "https://bookapi.bignerdranch.com/courses.json"
// let requestString: String = "https://bookapi.bignerdranch.com/private/courses.json"
if let url: NSURL? = NSURL(string: requestString) {
let request: NSURLRequest = NSURLRequest(URL: url!)
let dataTask : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
var jsonObject: [JSON] = JSON(data: data).arrayValue
self.courses = JSON(data: data)
dispatch_async(dispatch_get_main_queue(), { _ in
println( self.courses?.debugDescription )
})
});
dataTask.resume()
}
}
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
var userIdString: String = "BigNerdRanch"
var passwordString: String = "AchieveNerdvana"
println( "Received challenge, responding with UID: \(userIdString) PWD: \(passwordString)")
var cred: NSURLCredential = NSURLCredential(user: userIdString,
password: passwordString,
persistence: NSURLCredentialPersistence.ForSession)
completionHandler( NSURLSessionAuthChallengeDisposition.UseCredential, cred )
}
}
Any ideas?
Thanks

If you comment out the URL without "private" in it and uncomment the URL wit "private" in it, it does not work. If you do it from a web browser (Chrome,Firefox,Safari, etcetera) "https://bookapi.bignerdranch.com/private/courses.json" enter the credentials "BigNerdRanch" for user ID "AchieveNerdvana" for password and it returns the expected JSON

Related

Alamofire 5 Adapting and Retrying Requests

I am trying to implement my OAuth2 flow using Alamofire 5.0.0-beta.3. As i can see the documentation is still for Alamofire 4 as stated in the github page as well.
I am trying to make the Oauth2 handler following the documentation for Alamofire 4. As the class names are changed, I am completely lost while making it.
This is the code that i am following:
class OAuth2Handler: RequestAdapter, RequestRetrier {
private typealias RefreshCompletion = (_ succeeded: Bool, _ accessToken: String?, _ refreshToken: String?) -> Void
private let sessionManager: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
private let lock = NSLock()
private var clientID: String
private var baseURLString: String
private var accessToken: String
private var refreshToken: String
private var isRefreshing = false
private var requestsToRetry: [RequestRetryCompletion] = []
// MARK: - Initialization
public init(clientID: String, baseURLString: String, accessToken: String, refreshToken: String) {
self.clientID = clientID
self.baseURLString = baseURLString
self.accessToken = accessToken
self.refreshToken = refreshToken
}
// MARK: - RequestAdapter
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) {
var urlRequest = urlRequest
urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
return urlRequest
}
return urlRequest
}
// MARK: - RequestRetrier
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: #escaping RequestRetryCompletion) {
lock.lock() ; defer { lock.unlock() }
if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 {
requestsToRetry.append(completion)
if !isRefreshing {
refreshTokens { [weak self] succeeded, accessToken, refreshToken in
guard let strongSelf = self else { return }
strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() }
if let accessToken = accessToken, let refreshToken = refreshToken {
strongSelf.accessToken = accessToken
strongSelf.refreshToken = refreshToken
}
strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) }
strongSelf.requestsToRetry.removeAll()
}
}
} else {
completion(false, 0.0)
}
}
// MARK: - Private - Refresh Tokens
private func refreshTokens(completion: #escaping RefreshCompletion) {
guard !isRefreshing else { return }
isRefreshing = true
let urlString = "\(baseURLString)/oauth2/token"
let parameters: [String: Any] = [
"access_token": accessToken,
"refresh_token": refreshToken,
"client_id": clientID,
"grant_type": "refresh_token"
]
sessionManager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { [weak self] response in
guard let strongSelf = self else { return }
if
let json = response.result.value as? [String: Any],
let accessToken = json["access_token"] as? String,
let refreshToken = json["refresh_token"] as? String
{
completion(true, accessToken, refreshToken)
} else {
completion(false, nil, nil)
}
strongSelf.isRefreshing = false
}
}
}
This is how to use this for alamofire 4:
let baseURLString = "https://some.domain-behind-oauth2.com"
let oauthHandler = OAuth2Handler(
clientID: "12345678",
baseURLString: baseURLString,
accessToken: "abcd1234",
refreshToken: "ef56789a"
)
let sessionManager = SessionManager()
sessionManager.adapter = oauthHandler
sessionManager.retrier = oauthHandler
let urlString = "\(baseURLString)/some/endpoint"
sessionManager.request(urlString).validate().responseJSON { response in
debugPrint(response)
}
This is the link i am following to implement this.
https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests
Look at something like this.
struct EnvironmentInterceptor: RequestInterceptor {
func adapt(_ urlRequest: URLRequest, for session: Session, completion: #escaping (Result<URLRequest>) -> Void) {
var adaptedRequest = urlRequest
guard let token = AtraqService.shared.user?.token.accessToken else {
completion(.success(adaptedRequest))
return
}
adaptedRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
completion(.success(adaptedRequest))
}
func retry(_ request: Request, for session: Session, dueTo error: Error, completion: #escaping (RetryResult) -> Void) {
if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 {
//get token
}
}
}
Then
Session(configuration: configuration, interceptor: EnvironmentInterceptor())
Finally
request().validate().response...
If Alamofire 5 is not intercepting (adapting or retrying) your requests for some reason, then just try to check the delegate signature out as described here.
func adapt(_ urlRequest: URLRequest, for session: Session, completion: #escaping (AFResult<URLRequest>) -> Void) {
var modifiedURLRequest = urlRequest
let apiToken = config.apiToken
modifiedURLRequest.setValue(apiToken, forHTTPHeaderField: Constants.apiTokenHeader)
completion(.success(modifiedURLRequest))
}
func retry(_ request: Request, for session: Session, dueTo error: Error, completion: #escaping (RetryResult) -> Void) {
completion(.doNotRetry)
}
Here's the difference (look at the signature):
func adapt(_ urlRequest: URLRequest, for session: Alamofire.Session, completion: #escaping (AFResult<URLRequest>) -> Void) {
var modifiedURLRequest = urlRequest
let apiToken = config.apiToken
modifiedURLRequest.setValue(apiToken, forHTTPHeaderField: Constants.apiTokenHeader)
completion(.success(modifiedURLRequest))
}
func retry(_ request: Alamofire.Request, for session: Alamofire.Session, dueTo error: Error, completion: #escaping (RetryResult) -> Void) {
completion(.doNotRetry)
}

Swift - NSURLSession for Windows Authentication

I have this class here and inside the class is a method and I am trying to do an NSURLSession on an API that requires windows authentication username and password. I have followed the tutorial here https://gist.github.com/n8armstrong/5c5c828f1b82b0315e24
and came up with this:
let webservice = "https://api.com"
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let urlSession = NSURLSession(configuration: config)
class WebService: NSObject {
func loginUser(username: String, password: String) -> Bool {
let userPasswordString = "username#domain.com:Password"
let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions([])
let authString = "Basic \(base64EncodedCredential)"
config.HTTPAdditionalHeaders = ["Authorization" : authString]
let requestString = NSString(format:"%#", webservice) as String
let url: NSURL! = NSURL(string: requestString)
let task = urlSession.dataTaskWithURL(url) {
(let data, let response, let error) in
if (response as? NSHTTPURLResponse) != nil {
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(dataString)
}
}
task.resume()
return true
}
}
but when I run this I get a 401 error: 401 - Unauthorized: Access is denied due to invalid credentials.
I have confirmed the URL to the API is correct. Same with the username and password. What am I doing wrong?
I was able to fix this by doing the following:
var credential: NSURLCredential!
func loginUser(username: String, password: String) -> Bool {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
credential = NSURLCredential(user:username, password:password, persistence: .ForSession)
let requestString = NSString(format:"%#", webservice) as String
let url: NSURL! = NSURL(string: requestString)
let task = session.dataTaskWithURL(url, completionHandler: {
data, response, error in
dispatch_async(dispatch_get_main_queue(),
{
if(error == nil)
{
print("Yay!")
}
else
{
print("Naw!")
}
})
})
task.resume()
return true
}
and then adding NSURLSessionDelegate methods:
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
if challenge.previousFailureCount > 0
{
completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
}
else
{
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust:challenge.protectionSpace.serverTrust!))
}
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credential)
}

Swift Long Polling

I am trying to connect to a url and then receive updates from it, as it continuously returns new data in a method called HTTP Long Polling. I have found this example HTTP Long Polling in Swift but it simply isn't working. Data is returned once but then doesn't continuously return, and it works in CURL. Here is my code:
public class LongPollingRequest: NSObject {
var GlobalUserInitiatedQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)
}
var GlobalBackgroundQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.rawValue), 0)
}
weak var longPollDelegate: LongPollingDelegate?
var request: NSMutableURLRequest?
init(delegate:LongPollingDelegate){
longPollDelegate = delegate
}
public func poll(username: String!, token: String!, vehicleID: String!){
let loginString = NSString(format: "%#:%#", username, token)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])
// create the request
let url = NSURL(string:"https://streaming.vn.teslamotors.com/stream/\(vehicleID)/?values=speed,odometer,soc,elevation,est_heading,est_lat,est_lng,power,shift_state")!
request = NSMutableURLRequest(URL: url)
request!.HTTPMethod = "GET"
request!.setValue("text/json", forHTTPHeaderField: "content-type")
request!.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
poll()
}
private func poll(){
dispatch_async(GlobalBackgroundQueue) {
self.longPoll()
}
}
private func longPoll() -> Void{
autoreleasepool{
do{
print("starting request: \(request?.HTTPBody)")
let urlSession = NSURLSession.sharedSession()
let dataTask = urlSession.dataTaskWithRequest(self.request!, completionHandler: {
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if( error == nil ) {
self.longPollDelegate?.dataRecieved(data)
self.poll()
} else {
self.longPollDelegate?.errorRecieved(error)
}
})
dataTask.resume()
}
}
}

Basic authentication with UIWebView

I read a lot of post on SO on how I could be able to apply basic authentication.
I've produced this code but it does not show the log on page, only a white page is displayed. Credentials that I use works in the browser, so this is not the problem. My delegates are ok.
I can't figure out where my code fails:
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
self.loadPage()
}
func loadPage() {
let url = "mypage.com/auht/Logon.do"
let request = NSMutableURLRequest(URL: NSURL(string: url)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 12)
webView.loadRequest(request)
}
// MARK: NSURLConnectionDelegate Delegates
func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
if challenge.previousFailureCount == 0 {
authenticated = true
let credential = NSURLCredential(user: "m.rinaldi13", password: "299792,458km/s", persistence: NSURLCredentialPersistence.ForSession)
challenge.sender.useCredential(credential, forAuthenticationChallenge: challenge)
} else {
challenge.sender.cancelAuthenticationChallenge(challenge)
}
}
// MARK: Web View Delegates
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if authenticated == nil {
authenticated = false
NSURLConnection(request: request, delegate: self)
return false
}
return true
}
Any help/tip will be appreciated!
I find a solution by my self, excluding all this boring passeges.
func doRequestWithBasicAuth(completion : (success : Bool, html: String?, error : NSError?) -> Void) {
if let user = self.user {
let loginString = NSString(format: "%#:%#", user.login!, user.pwd!)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(nil)
let url = NSURL(string: user.service!.getURL())
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
if error == nil {
let htmlString = NSString(data: data, encoding: NSUTF8StringEncoding)
completion(success: true, html: htmlString as? String, error: nil)
} else {
completion(success: false, html: nil, error: error)
}
}
} else {
completion(success: false, html: nil, error: NSError())
}
}
Then you can evenly display page on web view in this way:
self.doRequestWithBasicAuth({ (success, html, error) -> Void in
if error == nil {
self.webView.loadHTMLString(string: html, baseURL: <yourNSURL>)
}
})
Obviously you can (had) to beautify code, like creating a class for model User:
class User {
var login: String?
var pwd: String?
func valueForHeaderFieldAuthorization() -> String {
let loginString = NSString(format: "%#:%#", user.login!, user.pwd!)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(nil)
return "Basic \(base64LoginString)"
}
}

How to make an HTTP request + basic auth in Swift

I have a RESTFull service with basic authentication and I want to invoke it from iOS+swift. How and where I must provide Credential for this request?
My code (sorry, I just start learn iOS/obj-c/swift):
class APIProxy: NSObject {
var data: NSMutableData = NSMutableData()
func connectToWebApi() {
var urlPath = "http://xx.xx.xx.xx/BP3_0_32/ru/hs/testservis/somemethod"
NSLog("connection string \(urlPath)")
var url: NSURL = NSURL(string: urlPath)
var request = NSMutableURLRequest(URL: url)
let username = "hs"
let password = "1"
let loginString = NSString(format: "%#:%#", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)
let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromMask(0))
request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self)
connection.start()
}
//NSURLConnection delegate method
func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
println("Failed with error:\(error.localizedDescription)")
}
//NSURLConnection delegate method
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
//New request so we need to clear the data object
self.data = NSMutableData()
}
//NSURLConnection delegate method
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
//Append incoming data
self.data.appendData(data)
}
//NSURLConnection delegate method
func connectionDidFinishLoading(connection: NSURLConnection!) {
NSLog("connectionDidFinishLoading");
}
}
You provide credentials in a URLRequest instance, like this in Swift 3:
let username = "user"
let password = "pass"
let loginString = String(format: "%#:%#", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
// create the request
let url = URL(string: "http://www.example.com/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)
Or in an NSMutableURLRequest in Swift 2:
// set up the base64-encoded credentials
let username = "user"
let password = "pass"
let loginString = NSString(format: "%#:%#", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])
// create the request
let url = NSURL(string: "http://www.example.com/")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)
swift 4:
let username = "username"
let password = "password"
let loginString = "\(username):\(password)"
guard let loginData = loginString.data(using: String.Encoding.utf8) else {
return
}
let base64LoginString = loginData.base64EncodedString()
request.httpMethod = "GET"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
//create authentication base 64 encoding string
let PasswordString = "\(txtUserName.text):\(txtPassword.text)"
let PasswordData = PasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = PasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
//let base64EncodedCredential = PasswordData!.base64EncodedStringWithOptions(nil)
//create authentication url
let urlPath: String = "http://...../auth"
var url: NSURL = NSURL(string: urlPath)
//create and initialize basic authentication request
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"
//You can use one of below methods
//1 URL request with NSURLConnectionDataDelegate
let queue:NSOperationQueue = NSOperationQueue()
let urlConnection = NSURLConnection(request: request, delegate: self)
urlConnection.start()
//2 URL Request with AsynchronousRequest
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
//2 URL Request with AsynchronousRequest with json output
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("\(jsonResult)")
})
//3 URL Request with SynchronousRequest
var response: AutoreleasingUnsafePointer<NSURLResponse?>=nil
var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:nil)
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("\(jsonResult)")
//4 URL Request with NSURLSession
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let authString = "Basic \(base64EncodedCredential)"
config.HTTPAdditionalHeaders = ["Authorization" : authString]
let session = NSURLSession(configuration: config)
session.dataTaskWithURL(url) {
(let data, let response, let error) in
if let httpResponse = response as? NSHTTPURLResponse {
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(dataString)
}
}.resume()
// you may be get fatal error if you changed the request.HTTPMethod = "POST" when server request GET request
In Swift 2:
extension NSMutableURLRequest {
func setAuthorizationHeader(username username: String, password: String) -> Bool {
guard let data = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return false }
let base64 = data.base64EncodedStringWithOptions([])
setValue("Basic \(base64)", forHTTPHeaderField: "Authorization")
return true
}
}
go plain for SWIFT 3 and APACHE simple Auth:
func urlSession(_ session: URLSession, task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let credential = URLCredential(user: "test",
password: "test",
persistence: .none)
completionHandler(.useCredential, credential)
}
I had a similar problem trying to POST to MailGun for some automated emails I was implementing in an app.
I was able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.
// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
keys = NSDictionary(contentsOfFile: path)
}
if let dict = keys {
// variablize our https path with API key, recipient and message text
let mailgunAPIPath = dict["mailgunAPIPath"] as? String
let emailRecipient = "bar#foo.com"
let emailMessage = "Testing%20email%20sender%20variables"
// Create a session and fill it with our request
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler#<my domain>.com%3E&to=reservations#<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)
// POST and report back with any errors and response codes
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:
https://API:key-<my key>#api.mailgun.net/v3/<my domain>.com/messages?
Hope this helps offers a solution to someone trying to avoid using 3rd party code for their POST requests!
my solution works as follows:
import UIKit
class LoginViewController: UIViewController, NSURLConnectionDataDelegate {
#IBOutlet var usernameTextField: UITextField
#IBOutlet var passwordTextField: UITextField
#IBAction func login(sender: AnyObject) {
var url = NSURL(string: "YOUR_URL")
var request = NSURLRequest(URL: url)
var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
func connection(connection:NSURLConnection!, willSendRequestForAuthenticationChallenge challenge:NSURLAuthenticationChallenge!) {
if challenge.previousFailureCount > 1 {
} else {
let creds = NSURLCredential(user: usernameTextField.text, password: passwordTextField.text, persistence: NSURLCredentialPersistence.None)
challenge.sender.useCredential(creds, forAuthenticationChallenge: challenge)
}
}
func connection(connection:NSURLConnection!, didReceiveResponse response: NSURLResponse) {
let status = (response as NSHTTPURLResponse).statusCode
println("status code is \(status)")
// 200? Yeah authentication was successful
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
You can use this class as the implementation of a ViewController. Connect your fields to the IBOutlet annotated vars and your Button to the IBAction annotated function.
Explanation:
In function login you create your request with NSURL, NSURLRequest and NSURLConnection.
Essential here is the delegate which references to this class (self).
For receiving the delegates calls you need to
Add the protocol NSURLConnectionDataDelegate to the class
Implement the protocols' function "connection:willSendRequestForAuthenticationChallenge"
This is used for adding the credentials to the request
Implement the protocols' function "connection:didReceiveResponse"
This will check the http response status code
I am calling the json on login button click
#IBAction func loginClicked(sender : AnyObject){
var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err1: NSError?
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary
println("json2 :\(json2)")
if(err) {
println(err!.localizedDescription)
}
else {
var success = json2["success"] as? Int
println("Succes: \(success)")
}
})
task.resume()
}
Here, I have made a seperate dictionary for the parameters.
var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionary
return params
}
Working example for SwiftUI iOS15 async/await
struct ExampleJSONService {
let passwordString = "user:password"
let configuration = URLSessionConfiguration.default
enum ExampleJSONServiceError: Error {
case failed
case failedToDecode
case invalidStatusCode
}
func fetchStuff(for myID:String) async throws -> [Stuff] {
let passwordData = passwordString.data(using:String.Encoding.utf8)!
let base64EncodedCredential = passwordData.base64EncodedString()
let authString = "Basic \(base64EncodedCredential)"
let session = URLSession(configuration: configuration)
configuration.httpAdditionalHeaders = ["Authorization" : authString]
let dataUrl = "https://toto.org/stuff/\(myID)/data.json"
let url = URL(string: dataUrl)!
var urlRequest = URLRequest(url: url)
urlRequest.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
urlRequest.httpMethod = "GET"
let (data, response) = try await session.data(for: urlRequest)
guard let response = response as? HTTPURLResponse,
response.statusCode == 200 else {
throw PrixJSONServiceError.invalidStatusCode
}
let decodedData = try JSONDecoder().decode([Prix].self, from: data)
return decodedData
}
}

Resources