I have been searching for 2 days now (I linked the threads I used below) and so far nothing has worked. My code is as below for Serializing the data that the api sends back and trying to save it in User Defaults using Swift 4.
do{
let token = try JSONSerialization.jsonObject(with: data!, options: [])
print(token)
UserDefaults.standard.set(token, forKey: "savedToken")
}catch{
if httpResponse.statusCode == 401{
Helper.showAlert(viewController: self, title: "Oops", message: "Username or Password Incorrect")
}
print(error)
}
} else if let error = error {
Helper.showAlert(viewController: self, title: "Well Damn", message: "Ay chief we have no idea what just happened but it didn't work")
print(error)
}
When I try to retrieve the data that I thought was stored in the key "savedToken",
let tokenData = UserDefaults.standard.object(forKey: "savedToken")
I have it print tokenData into the console and it says nil. I tried the method in this thread and it still says that it is nil. I did have to remove the "if" command from the answer so I can use the value. This is the code I'm using that requires the saved token;
let tokenData = UserDefaults.standard.object(forKey: "savedToken")
let areaHeaders = [
"Authorization": "token \(tokenData)", // <-- this is where I need the token.
"Content-Type": "application/x-www-form-urlencoded",
"anonym": "true",
"cache-control": "no-cache",
"Postman-Token": "0017837d-5229-46a3-98ff-58fe3aa09df9"
]
let areaData = NSMutableData(data: "undefined=undefined".data(using: String.Encoding.utf8)!)
let areaRequest = NSMutableURLRequest(url: NSURL(string: "http://localhost:8000/areas/sample/")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
areaRequest.httpMethod = "GET"
areaRequest.allHTTPHeaderFields = areaHeaders
areaRequest.httpBody = areaData as Data
let areaSession = URLSession.shared
let areaDataTask = areaSession.dataTask(with: areaRequest as URLRequest, completionHandler: { (data, response, error) -> Void in
if let data = data {
do{
let postData = try JSONSerialization.jsonObject(with: data, options: [])
print(postData)
}catch{
print(error)
}
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
areaDataTask.resume()
I am completely lost at this point. I've also tired this method too. All I'm trying to do is save the returned data that looks like this; to a Users Defaults or something where I can easily retrieve it.