Display lastName in application after retrieve value key in token Swift 4 - ios

I have another problem after my previous post.
i want to display lastname in application after i retrieve in value of token. here is my code to get value of lastname in token
// request = url of API
// token = I have already recovered the value of the token
request.addValue("Bearer \(token!)", forHTTPHeaderField: "Authorization")
//get information in token
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject]
let sub = json["sub"] as! [String: AnyObject]
// get value of lastName
let lastName = sub["lastname"] as! String
} catch {
print("error")
}
}.resume()
and now I want to display the lastname in the application
let headerMenu = HPMenuHeaderViewModel.init(lastName: "display lastname here..")
// display table view and information of user like lastname
let tableViewModel = HPMenuViewModel(titlePage: "Menu", array: arrayCellModel, headerMenuViewModel: headerMenu)
self.tableViewModel = tableViewModel
Can you Help Me please !

i have this fonction to get firstname, lastname, number
func loadMemberProfil(){
let token = HPWSLoginManager.shared().saveSuccessResponse.token
let url = URL(string: "http://51.38.36.76:40/api/v1/profile")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.addValue("Bearer \(token!)", forHTTPHeaderField: "Authorization")
//get information in token
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject]
let sub = json["sub"] as! [String: AnyObject]
let firstName = sub["firstname"] as! String
let lastName = sub["lastname"] as! String
let number = sub["internationalFormat"] as! String
} catch {
print("error")
}
}.resume()
}
and in viewDidLoad() i want to display in this function
func initTableViewModel() {
let headerMenu = HPMenuHeaderViewModel.init(firstName: "...", lastName: "...", numberString: "...")
let tableViewModel = HPMenuViewModel(titlePage: "Menu", array: arrayCellModel, headerMenuViewModel: headerMenu)
self.tableViewModel = tableViewModel
}

You can achieve that by using Closures.
func loadMemberProfil(completion: ((_ sub : [String: AnyObject]) -> Void)?) {
let token = HPWSLoginManager.shared().saveSuccessResponse.token
let url = URL(string: "http://51.38.36.76:40/api/v1/profile")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.addValue("Bearer \(token!)", forHTTPHeaderField: "Authorization")
//get information in token
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject]
let sub = json["sub"] as! [String: AnyObject]
if completion != nil{
completion(sub)
}
} catch {
print("error")
}
}.resume()
}
Then call this method, where you want to set the last name
func initTableViewModel() {
self.loadMemberProfil { (sub) in
let headerMenu = HPMenuHeaderViewModel.init(firstName: "\(sub["firstname"])", lastName: "\(sub["lastname"])", numberString: "\(sub["internationalFormat"])")
let tableViewModel = HPMenuViewModel(titlePage: "Menu", array: arrayCellModel, headerMenuViewModel: headerMenu)
self.tableViewModel = tableViewModel
}
}

Related

Access Value of a Same key in a dictionary of outside function

I want to access the same key of a dictionary that called name and I cant change the value of key because it is on server : here is my code :
func infoUser(complition:#escaping ([String:Any]) -> Void) {
let url = URL(string: "\(offerUrl)/api/user")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "GET" //set http method as POST
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue( "bearare \(profileKeychain["token"]!)", forHTTPHeaderField: "Authorization")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
print("data is : \(data)")
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print("this is json format: \(json)")
// handle json ...
guard let YourName = json["name"] as? String else { return }
guard let YourAddress = json["address"] as? String else { return }
guard let YourPhone = json["telephone"] as? String else { return }
guard let YourEmail = json["email"] as? String else { return }
guard let city = json["city"] as? [String: Any] else { return }
guard let title = city["title"] as? String else { return }
guard let country = json["country"] as? [String: Any] else { return }
guard let names = country["name"] as? String else { return }
let dict = ["name":YourName,"address":YourAddress,"telephone":YourPhone,"email":YourEmail,"city":city,"title":title,"country":country,"name" : names] as [String : Any]
complition(dict)
}
} catch let error {
print("error is this : \(error.localizedDescription)")
}
})
task.resume()
}
I want to access the value of names in country which its key in name like the name of user
and also this is a completion handler that I use it I called it from viewdidLoad() function :
override func viewDidLoad() {
super.viewDidLoad()
if profileKeychain["token"] != "" {
infoUser { dict in
DispatchQueue.main.async {
self.yourNamelbl.text = dict["name"] as? String
self.yourPhonelbl.text = dict["telephone"] as? String
self.yourCitylbl.text = dict["title"] as? String
self.yourMaillbl.text = dict["email"] as? String
self.yourAddresslbl.text = dict["address"] as? String
// this line
self.countryNamelbl.text = dict["name" ] as? String }}}
and in simulator the name of country and the name of user is same in labels but I dont want to happen this, what's your idea?
thanks for attention
You are overwriting the value for "name" key.
let dict = [
"name": YourName, // First write happens here
"address": YourAddress,
"telephone": YourPhone,
"email": YourEmail,
"city": city,
"title": title,
"country": country,
"name" : names // Second write, The problem is here
] as [String: Any]
UPDATE
You already have name nested inside country dictionary, so you don't need to store it one more time at the top level.
You can remove the second write from above code "name": names part and use it like following in your viewDidLoad().
let country = dict["country"] as? [String: Any]
self.countryNamelbl.text = country?["name"] as? String

How to get Array of an json Object swift

I want to get the array from the JSON Object
Here is my Code:
let url = URL(string:"http://192.168.0.117/rest/login.php")
let parameters = ["email": email , "pwd":password]
var request = URLRequest(url : url!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject:parameters, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
session.dataTask(with: request, completionHandler: { (data, response, error) in
if let data = data {
do {
let json = try? JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
if let json = json {
print("HERE SHOULD BE YOUR JSON OF LOGIN : \(json)")
let status = json["status"] as! String
let datas = json["data"] as! String
print("Here is the Data : \(datas)")
print("here LOIGN : \(status)")
if status == "200"
{
DispatchQueue.main.async
{
self.performSegue(withIdentifier: "dosigninEmp", sender: self)
}
} else if status == "204"
{
self.displayMessage(userMessage: "Not Authorized User")
}
}
}
} else {
print("Error \(String(describing: error?.localizedDescription))")
}
}).resume()
I am getting the Output as:
HERE SHOULD BE YOUR JSON OF LOGIN : ["status": 200, "data": {
"emp_id" = 1004;
type = emp;
}, "Message": Auth Succesful]
how i can get "type" because i am getting status and using segue but now i want to fetch status as well as type to use segue and i am unable to get type
Any Help would be appreciated
I think converting your data in json will give proper json format of string, array & dictionaries. And that's why it would give the datas in Dictionary:
print("HERE SHOULD BE YOUR JSON OF LOGIN : \(json)")
let status = json["status"] as! String
let datas = json["data"] as! String
print("Here is the Data : \(datas)")
print("here LOIGN : \(status)")
Can change these lines into:
var type = ""
var datas = [String: AnyObject]()
if let data = json["data"] as? [String: AnyObject], let typeStr = data["type"] as? String {
datas = data
type = typeStr
}
print("Here is the Data : \(datas)")
print("Here Type : \(type)")

Api is not showing serialized json output

I have created simple login screen attached with loginViewController.swift. Here are the urls
let login_url = "http://192.168.100.11:9000//users/authenticate"
let checksession_url = "http://192.168.100.11:9000//users/authenticate"
I have simple login api. The web service it is showing response on post man web service but it is not displaying serialized json output on Xcode. How to get serialize json from url?
The api is getting two parameters from username="andrews" and password="admin2"
func login_now(username:String, password:String){
let post_data: NSDictionary = NSMutableDictionary()
post_data.setValue(username, forKey: "username")
post_data.setValue(password, forKey: "password")
let url:URL = URL(string: login_url)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
var paramString = ""
for (key, value) in post_data {
paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
}
let endIndex = paramString.index(paramString.endIndex, offsetBy: -1)
let truncated = paramString.substring(to: endIndex)
paramString=truncated
print(paramString) // This won't consist of last &
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data!, options: [])
//////////////here json object is not formed to get json output
print("abc")
print(json)
}
catch
{
return
}
guard let server_response = json as? NSDictionary else
{
return
}
if let data_block = server_response["data"] as? NSDictionary
{
if let session_data = data_block["session"] as? String
{
self.login_session = session_data
let preferences = UserDefaults.standard
preferences.set(session_data, forKey: "session")
DispatchQueue.main.async(execute: self.LoginDone)
}
}
})
task.resume()
}
Here json object is not formed to get serialized json output.how to get the serialized json out put on Nslog? You can download the project from this link.

How to parse a api for swift 3?

Have been researching on the parsing for quite a bit. With plethora of information avilable for JSON nothing seems to explain how to do in a sensible way to extract information with swift 3.
This is what got so far
func getBookDetails() {
let scriptUrl = "https://www.googleapis.com/books/v1/volumes?q=isbn:9781451648546" .
let myurl = URL(string:scriptUrl)
let request = NSMutableURLRequest(url: myurl!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: myurl! ) { (data, response, error) in
if error != nil{
print("THIS ERROR",error!)
return
} else{
if let mydata = data{
do{
let myJson = try (JSONSerialization.jsonObject(with: mydata, options: JSONSerialization.ReadingOptions.mutableContainers)) as AnyObject
// print("this is the MY JSON",myJson) ---> prints out the json
if let dictonary = myJson["items"] as AnyObject? {
print("the DICTONARY",dictonary) // ----> OUTPUT
if let dictonaryAA = dictonary["accessInfo"] as AnyObject? {
print("the accessInfo",dictonaryAA)
}
}
} catch{
print("this is the in CATCH")
}
} //data
}
}
task.resume()
}
}
OUTPUT :
the DICTONARY (
{
accessInfo = {
accessViewStatus = SAMPLE;
country = US;
=============
RELEVANT DATA as in https://www.googleapis.com/books/v1/volumes?
q=isbn:9781451648546"
==========================
title = "Steve Jobs";
};
}
)
Just need to parse through the json data to get the name, author and title of the book with reference to isbn.
Know there should be a better way to do things that is easily understandable to someone new into the language
You can parse the api in two ways
Using URLSession:
let rawDataStr: NSString = "data={\"mobile\":\"9420....6\",\"password\":\"56147180..1\",\"page_no\":\"1\"}"
self.parsePostAPIWithParam(apiName: "get_posts", paramStr: rawDataStr){ ResDictionary in
// let statusVal = ResDictionary["status"] as? String
self.postsDict = (ResDictionary["posts"] as! NSArray!) as! [Any]
print("\n posts count:",self.postsDict.count)
}
func parsePostAPIWithParam(apiName:NSString, paramStr:NSString,callback: #escaping ((NSDictionary) -> ())) {
var convertedJsonDictResponse:NSDictionary!
let dataStr: NSString = paramStr
let postData = NSMutableData(data: dataStr.data(using: String.Encoding.utf8.rawValue)!)
let request = NSMutableURLRequest(url: NSURL(string: "http://13.12..205.248/get_posts/")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = nil
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error as Any)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse as Any)
do{
if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
convertedJsonDictResponse = convertedJsonIntoDict.object(forKey: apiName) as? NSDictionary
// callback for response
callback(convertedJsonDictResponse)
}
} catch let error as NSError {
print(error)
}
}
Using Alamofire
func AlamofirePOSTRequest() {
let urlString = "http://13.12..205.../get_posts/"
let para = ["data": "{\"mobile\":\"9420....6\",\"password\":\"56147180..1\",\"page_no\":\"1\"}"]
Alamofire.request(urlString, method: .post, parameters: para , headers: nil).responseJSON {
response in
switch response.result {
case .success:
print("response: ",response)
let swiftyJsonVar = JSON(response.result.value!)
if let resData = swiftyJsonVar["posts"].arrayObject {
self.postsDict = resData as! [[String:AnyObject]]
}
print("\n \n alomafire swiftyJsonVar: ",swiftyJsonVar)
break
case .failure(let error):
print(error)
}
}
}
})
dataTask.resume()
}
First of all, all JSON types are value types in Swift 3 so the most unspecified type is Any, not AnyObject.
Second of all, there are only two collection types in the JSON type set, dictionary ([String:Any]) and array ([Any], but in most cases [[String:Any]]). It's never just Any nor AnyObject.
Third of all, the given JSON does not contain a key name.
For convenience let's use a type alias for a JSON dictionary:
typealias JSONDictionary = [String:Any]
The root object is a dictionary, in the dictionary there is an array of dictionaries for key items. And pass no options, .mutableContainers is nonsense in Swift.
guard let myJson = try JSONSerialization.jsonObject(with: mydata) as? JSONDictionary,
let items = myJson["items"] as? [JSONDictionary] else { return }
Iterate through the array and extract the values for title and authors which is an array by the way. Both values are in another dictionary for key volumeInfo.
for item in items {
if let volumeInfo = item["volumeInfo"] as? JSONDictionary {
let title = volumeInfo["title"] as? String
let authors = volumeInfo["authors"] as? [String]
print(title ?? "no title", authors ?? "no authors")
The ISBN information is in an array for key industryIdentifiers
if let industryIdentifiers = volumeInfo["industryIdentifiers"] as? [JSONDictionary] {
for identifier in industryIdentifiers {
let type = identifier["type"] as! String
let isbn = identifier["identifier"] as! String
print(type, isbn)
}
}
}
}
You are doing wrong in this line
if let dictonaryAA = dictonary["accessInfo"] as AnyObject?
because dictonary here is an array not dictionary. It is array of dictionaries. So as to get first object from that array first use dictonary[0], then use accessInfo key from this.
I am attaching the code for your do block
do{
let myJson = try (JSONSerialization.jsonObject(with: mydata, options: JSONSerialization.ReadingOptions.mutableContainers)) as AnyObject
// print("this is the MY JSON",myJson) ---> prints out the json
if let array = myJson["items"] as AnyObject? {
print("the array",array) // ----> OUTPUT
let dict = array.object(at: 0) as AnyObject//Master Json
let accessInf = dict.object(forKey: "accessInfo") //Your access info json
print("the accessInfo",accessInf)
}
}
Hope this helps you.

swift what is the timing to reload data after NSURLSession POST request

I am trying to show some data in tableView after getting JSON. However, it is failed by using tableView.reloadData() . I menu delay.
My situation is that the tableView will reload data after 14-20 seconds of getting JSON, but it will reload data immediately when user active the table.
Swift:
func getJson(word: String){
let url: NSURL = NSURL(string: "MyPHP.php")!
let session = NSURLSession.sharedSession()
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let bodydata = "label=\(word)"
request.HTTPBody = bodydata.dataUsingEncoding(NSUTF8StringEncoding)
if bodydata != " " {
let task = session.dataTaskWithRequest(request) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if(statusCode == 200) {
self.libraryArray.removeAll()
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
print(json)
if let book = json["Book"] as? [[String: AnyObject]]{
for books in book {
if let BookName = book["Name"] as? [String: AnyObject] {
let name = BookName["name"] as? String
let author = BookName["author"] as? String
let bookDict = [
"name": name,
"id": id,
"author": author]
self.libraryArray.append(bookDict)
self.tableView.reloadData() // has 14- 20 seconds delay, but the JSON has already received
}
}
}
}catch {
print("error:\(error)")
}
}
}
task.resume()
// self.tableView.reloadData() if i try to reload here, it will not be executed.
}
}
#IBAction func Next(sender: AnyObject) {
self.getJson("someString")
//self.tableView.reloadData() if i try to reload here, it will be fail.
}
what is the problem of the delay? How to solve it?
What is the right timing to reload tableView?
Replace your self.tableView.reloadData() with this
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
You are asking the table to reload while you didn't finish parsing the json. you do that after every Book parsing. you should do it after you finish parsing. the only explanation of the delay is that you have a huge data that is taking all that time for parsing!! Is that possible?
func getJson(word: String){
let url: NSURL = NSURL(string: "MyPHP.php")!
let session = NSURLSession.sharedSession()
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let bodydata = "label=\(word)"
request.HTTPBody = bodydata.dataUsingEncoding(NSUTF8StringEncoding)
if bodydata != " " {
let task = session.dataTaskWithRequest(request) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if(statusCode == 200) {
self.libraryArray.removeAll()
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
print(json)
if let book = json["Book"] as? [[String: AnyObject]]{
for books in book {
if let BookName = book["Name"] as? [String: AnyObject] {
let name = BookName["name"] as? String
let author = BookName["author"] as? String
let bookDict = [
"name": name,
"id": id,
"author": author]
self.libraryArray.append(bookDict)
self.tableView.reloadData() // has 14- 20 seconds delay, but the JSON has already received
}
}
}
}catch {
print("error:\(error)")
}
self.tableView.reloadData() // <<----- HERE
}
}
task.resume()
// self.tableView.reloadData() if i try to reload here, it will not be executed.
}
}
#IBAction func Next(sender: AnyObject) {
self.getJson("someString")
//self.tableView.reloadData() if i try to reload here, it will be fail.
}

Resources