Skip to content

Instantly share code, notes, and snippets.

@sebug
Created December 9, 2015 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebug/a8bdc870ecf22270d148 to your computer and use it in GitHub Desktop.
Save sebug/a8bdc870ecf22270d148 to your computer and use it in GitHub Desktop.
import Foundation
struct APIService {
let baseUrl = "redacted"
let applicationId = "redacted"
let eventCode = "redacted"
let token: String?
func login(c: Credentials, andThen: APIService -> ()) -> () {
let encodedPassword = c.encodedPassword().stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let urlToCall = baseUrl + "/API/Authenticate?ApplicationId=" +
applicationId + "&UserName=" + c.userName +
"&Password=" + encodedPassword! +
"&EventCodeList=" + self.eventCode
let request = NSMutableURLRequest()
request.URL = NSURL(string: urlToCall)
request.HTTPMethod = "GET"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
do {
let jsonResult: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.AllowFragments) as? NSObject
if (jsonResult != nil) {
andThen(BComAPIService(token: jsonResult as? String))
} else {
// couldn't load JSON, look at error
print("Error loading JSON")
}
} catch {
print("Error during authentication")
}
}
task.resume()
}
func getParticipantList(pageIndex: Int, pageSize: Int, andThen: [Participant] -> ()) {
var urlToCall = baseUrl + "/API/GetParticipantList?AuthenticationToken=" +
self.token!.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
urlToCall += "&EventCode=" + self.eventCode +
"&PageIndex=\(pageIndex)" +
"&PageSize=\(pageSize)"
print("Calling \(urlToCall)")
let request = NSMutableURLRequest()
request.URL = NSURL(string: urlToCall)
request.HTTPMethod = "GET"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
do {
let jsonResult: NSArray? = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.AllowFragments) as? NSArray
if (jsonResult != nil) {
var participants = [Participant]()
for o in jsonResult! {
let dict = o as! NSDictionary
var firstNameMaybe = dict["FirstName"] as? String
if firstNameMaybe == nil {
firstNameMaybe = ""
}
let part = Participant(identifier: dict["Identifier"] as! String,
firstName: firstNameMaybe!)
participants.append(part)
}
andThen(participants)
} else {
// couldn't load JSON, look at error
print("Error loading JSON")
}
} catch {
print("Error during authentication")
}
}
task.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment