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

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

Related

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

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
}
}

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)")

Assign Data using Grand Central Dispatch Swift 3

I created a Networking file for downloading data, and I want to assign the data to another view controller so I can populate a map with annotations. The data download successfully, but I can't get it to assign to the view controller. I can only get it working when I include the networking code in the view controller and use DispatchQueue.main.async. I want to keep the networking file and view controller separate. Any insights would be greatly appreciated. Apologies in advance for the many lines of code.
The networking file is as follows:
import UIKit
class Networking {
static let shared = Networking()
var objects = [Any]()
func getData (_ completionHandler:#escaping (Location?) -> ()) {
//Create the url with NSURL reuqest
let url = URL(string: "http://localhost:3000/locations")
let request = NSMutableURLRequest(url: url! as URL)
//Set HTTP method as GET
request.httpMethod = "GET"
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Accept")
//Create dataTask using the session object to send data to the server
URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
guard let data = data,
let dataStore = String(data: data, encoding: String.Encoding.utf8) else {
print("Could not find network")
completionHandler(nil)
return
}
guard error == nil else {
print("Error calling GET")
completionHandler(nil)
return
}
let HTTPResponse = response as! HTTPURLResponse
let statusCode = HTTPResponse.statusCode
if (statusCode == 200) {
print("Files downloaded successfully. \(dataStore)" )
} else {
completionHandler(nil)
return
}
//Create json object from data
do {
let json = try! JSONSerialization.jsonObject(with: data , options: []) as? [[String: Any]]
let location: [Location] = []
if let array = json {
for i in 0 ..< array.count {
if let data_object = array[i] as? [String: Any] {
if let _id = data_object["_id"] as? String,
let name = data_object["name"] as? String,
let imageID = data_object["imageID"] as? String,
let category = data_object["category"] as? String,
let details = data_object["details"] as? String,
let latitude = data_object["latitude"] as? Double,
let longitude = data_object["longitude"] as? Double {
var dictionary = [_id, name, imageID, category, details, latitude, longitude] as [Any]
dictionary.append(location)
}
}
}
}
}
}.resume()
}
}
The model is as follows:
class Location {
var _id : String
var name : String
var imageID : String
var category : String
var details : String
var latitude : Double
var longitude : Double
init?(_id: String, name: String, imageID: String, category: String, details: String, latitude: Double, longitude: Double) {
self._id = _id
self.name = name
self.imageID = imageID
self.category = category
self.details = details
self.latitude = latitude
self.longitude = longitude
}
}
The view controller is as follows:
class MapViewController: UIViewController, MGLMapViewDelegate, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
Networking.shared.getData { (locations) in
}
populateMap()
}
func populateMap (){
let point = MGLPointAnnotation()
for location in locations {
let coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude )
point.coordinate = coordinate
point.title = location.name
point.subtitle = location.category
self.mapView.addAnnotation(point)
}
}
You are executing completion blocks only in failure cases. Execute the completion block once you have managed to parse the data and pass the array as parameter to closure/block.
import UIKit
class Networking {
static let shared = Networking()
var objects = [Any]()
func getData (_ completionHandler:#escaping ([Location]?) -> ()) {
//Create the url with NSURL reuqest
let url = URL(string: "http://localhost:3000/locations")
let request = NSMutableURLRequest(url: url! as URL)
//Set HTTP method as GET
request.httpMethod = "GET"
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Accept")
//Create dataTask using the session object to send data to the server
URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
guard let data = data,
let dataStore = String(data: data, encoding: String.Encoding.utf8) else {
print("Could not find network")
completionHandler(nil)
return
}
guard error == nil else {
print("Error calling GET")
completionHandler(nil)
return
}
let HTTPResponse = response as! HTTPURLResponse
let statusCode = HTTPResponse.statusCode
if (statusCode == 200) {
print("Files downloaded successfully. \(dataStore)" )
} else {
completionHandler(nil)
return
}
//Create json object from data
do {
let json = try! JSONSerialization.jsonObject(with: data , options: []) as? [[String: Any]]
let location: [Location] = []
if let array = json {
for i in 0 ..< array.count {
if let data_object = array[i] as? [String: Any] {
if let _id = data_object["_id"] as? String,
let name = data_object["name"] as? String,
let imageID = data_object["imageID"] as? String,
let category = data_object["category"] as? String,
let details = data_object["details"] as? String,
let latitude = data_object["latitude"] as? Double,
let longitude = data_object["longitude"] as? Double {
var dictionary = [_id, name, imageID, category, details, latitude, longitude] as [Any]
dictionary.append(location) //am not sure of what this means test your code
completionHandler(location)
}
}
}
}
}
}.resume()
}
}
Few more mistakes in your code :
Your completion block expects Location as a parameter. but in your code you are creating an array of Locations.
let location: [Location] = []
So I have modified the completion block parameters to return array of locations
In your for loop you are creating
var dictionary = [_id, name, imageID, category, details, latitude, longitude] as [Any]
and appending it to dictionary.append(location) I have no idea what this code is. I believe what u actually trying to do is create a location object from the data and then add it to location array
location.append(your_new_location_object)
Hope it helps

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.

Values are not updating in my text label from api calling

I have one api calling, and I am passing one parameter value to that api. And I am doing append to one model data and from there I am trying to display in my label. But when I do api calling itself and try to print the label name , Its showing crash index out of range
func showprofileapi () {
let headers = [
"cache-control": "no-cache",
"postman-token": "4c933910-0da0-b199-257b-28fb0b5a89ec"
]
let jsonObj:Dictionary<String, Any> = [
"customerID" : "5"
]
if (!JSONSerialization.isValidJSONObject(jsonObj)) {
print("is not a valid json object")
return
}
if let postData = try? JSONSerialization.data(withJSONObject: jsonObj, options: JSONSerialization.WritingOptions.prettyPrinted) {
let request = NSMutableURLRequest(url: NSURL(string: "http://MyProfile.php")! as URL,
cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
///print(error)
} else {
DispatchQueue.main.async(execute: {
if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? Dictionary<String,AnyObject>
{
let status = json["status"] as? Int;
if(status == 1)
{
print("SUCCESS....")
if (json["myprofile"] as? NSDictionary) != nil
{
print("SUCCESS ......22....")
print(json)
DispatchQueue.main.async(execute: {
print("INSIDE CATEGORIES")
self.Profileddatas.append(MyProfiledData(json:json as NSDictionary))
print("Product Name : ", self.Profileddatas[0].custName)
})
}
}
}
})
}
})
dataTask.resume()
}
}
My above code is my api calling, And when I try to print the value in my console its crashing :
// print("Product Name : ", self.Profileddatas[0].custName)
My json output after api calling is :
{
"status": 1,
"message": "My Profile Details are.",
"myprofile": {
"CustomerName": "ram",
"CustomerEmail": "ram#gmail.com",
"CustomerMobile": "",
"CustomerAddress": "",
"CustomerUsername": "",
"CustomerPassword": " "
}
}
My append data model class is :
class MyProfiledData
{
var custName : String?
var custEmail : String?
var custMobile : String?
var custAddress : String?
var custUsername : String?
var custPassword : String?
init(json:NSDictionary)
{
self.custName = json["CustomerName"] as? String
self.custEmail = json["CustomerEmail"] as? String
self.custMobile = json["CustomerMobile"] as? String
self.custAddress = json["CustomerAddress"] as? String
self.custUsername = json["CustomerUsername"] as? String
self.custPassword = json["CustomerPassword"] as? String
}
}
Please help me out.
Thanks
change if (json["myprofile"] as? NSDictionary) != nil
to if let json = json["myprofile"] as? NSDictionary because your 'json' in the context of initializing MyProfiledData went wrong
You're accessing the JSON Data by it's wrong keys in Your MyProfileData Class. You have either pass the ["myprofile"] dict in the init(json) call by
if let myProfile = json["myprofile"] as? NSDictionary {
DispatchQueue.main.async(execute: {
self.Profiledatas.append(MyProfileData(json:myProfile))
})
}
or access it by their right Keys:
class MyProfiledData {
var custName : String?
var custEmail : String?
var custMobile : String?
var custAddress : String?
var custUsername : String?
var custPassword : String?
init(json:NSDictionary) {
self.custName = json["myprofile"]["CustomerName"] as? String
self.custEmail = json["myprofile"]["CustomerEmail"] as? String
self.custMobile = json["myprofile"]["CustomerMobile"] as? String
self.custAddress = json["myprofile"]["CustomerAddress"] as? String
self.custUsername = json["myprofile"]["CustomerUsername"] as? String
self.custPassword = json["myprofile"]["CustomerPassword"] as? String
}
}
In your init function it structure is not ok, it will be work if you send only my profile node of your json
{
"CustomerName": "ram",
"CustomerEmail": "ram#gmail.com",
"CustomerMobile": "",
"CustomerAddress": "",
"CustomerUsername": "",
"CustomerPassword": " "
}
use
self.Profileddatas.append(MyProfiledData(json:Json["myprofile"] as NSDictionary))
if (json["myprofile"] as? NSDictionary) != nil
{
print("SUCCESS ......22....")
print(json)
DispatchQueue.main.async(execute: {
print("INSIDE CATEGORIES")
self.Profileddatas.append(MyProfiledData(json:json["myprofile"] as! NSDictionary))
print("Product Name : ", self.Profileddatas[0].custName)
self.getvalue ()
})
}

Resources