Reputation: 185
I need to pass JWT token in order to get access to the data. How do I do it? I see the token in the console, but there is nothing in the tableView. What I actually want is: - Authenticate the user - Get the JWT token - Display the relevant courses
import UIKit
import Alamofire
class AvailableCoursesTableViewController: UITableViewController {
let url = "https://api.sis.kemoke.net/auth/login"
var parameters = ["email": "[email protected]", "password": "passwd"]
var token : HTTPHeaders = ["X-Auth-Token": ""]
//Custom struct for the data
struct Courses {
let course : String
init(dictionary: [String:String]) {
self.course = dictionary["course"] ?? ""
}
}
//Array which holds the courses
var courseData = [Courses]()
func authenticate() {
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: nil).responseJSON {
(response) in
self.token["X-Auth-Token"] = response.description
print(self.token)
}
}
// Download the courses
func downloadData() {
Alamofire.request("https://api.sis.kemoke.net/student/course", headers: token).responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
//Optional binding to handle exceptions
self.courseData.removeAll() // clean the data source array
if let json = response.result.value as? [[String:String]] {
for course in json {
self.courseData.append(Courses(dictionary: course))
}
self.tableView.reloadData()
}
}
}
Upvotes: 0
Views: 2406
Reputation: 7129
To download courses you have to put token in following way:
// Where otherParameter is any other parameter you want to pass
func downloadData(token : String, otherParameter : String)
{
let url: String = "https://api.sis.kemoke.net/student/course"
var request = URLRequest(url: NSURL(string: url) as! URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values: [String: Any] = ["otherParameter": otherParameter,"token": token]
request.httpBody = try! JSONSerialization.data(withJSONObject: values)
Alamofire.request(request)
.response { response in
let jsonData = JSON(data: response.data!)
print(jsonData)
print(response)
//Error check
//check if error is returned
if (response.error == nil) {
// Write your required functionality here
}
}
Upvotes: 2