How to get Array of an json Object swift - ios

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

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

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

How to parse JSON using Alamofire in Swift 3.0 without any third-party library

Here I want to parse JSON via url. This is what actual JSON data available on url. So I need to parse it and read in my app using Alamofire. But I 'm unable to do it.
JSON Data in my url.
{
"main": [
{
"date": "2017-01-11",
"USDARS": "15.8302",
"USDCLP": "670.400024",
"USDSDG": "6.407695"
},
{
"date": "2017-01-12",
"USDARS": "15.804999",
"USDCLP": "661.599976",
"USDSDG": "6.407697"
},
{
"date": "2017-01-13",
"USDARS": "15.839041",
"USDCLP": "659.200012",
"USDSDG": "6.407704"
},
{
"date": "2017-01-14",
"USDARS": "15.839041",
"USDCLP": "659.200012",
"USDSDG": "6.407704"
}
]
}
How do I read it using Alamofire in swift 3.0
Below is what actually I'm trying to parse above JSON data via url.
Alamofire.request("myurl") .responseJSON { response in
print("In Alamofire")
if let arr = response.result.value as? [String:AnyObject]
{
if let arr = response.result.value as? [NSDictionary]
{
let val1 = (arr["main"]["USDARS"] as? String)
print(val1)
//It does not print any thing.
}
}
}
Please help me. I'm new to it.
Top level json is [String:Any] and main is an array i.e. [[String:String]]
Alamofire.request("myurl") .responseJSON { response in
if let result = response.result.value as? [String:Any],
let main = result["main"] as? [[String:String]]{
// main[0]["USDARS"] or use main.first?["USDARS"] for first index or loop through array
for obj in main{
print(obj["USDARS"])
print(obj["date"])
}
}
}
You should use SwiftyJson, which is a library for json parsing, very usefull with Alamofire
In your case you can do something like this with swiftyJson :
//Array & Dictionary
var jsonArray: JSON = [
"main": ["date": "2017-01-11", "USDARS": "15.8302"]
]
let dateString = jsonArray["main"][0]["date"].string
print(dateString) = "2017-01-11"
#IBAction func btnget(_ sender: UIButton) {
let urlpath : String = "http://202.131.123.211/UdgamApi_v4/App_Services/UdgamService.asmx/GetAllTeacherData?StudentId=2011111"
let url = URL(string: urlpath)
var urlrequest = URLRequest(url: url!)
urlrequest.httpMethod = "GET"
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: urlrequest) { (data, response, error) in
do {
guard let getResponseDic = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject] else {
print("error trying to convert data to JSON")
return
}
// now we have the todo, let's just print it to prove we can access it
print(getResponseDic as NSDictionary)
let dic = getResponseDic as NSDictionary
let msg = dic.object(forKey: "message")
print(dic)
//let arrObj = dic.object(forKey: "teacherDetail") as! NSArray
//print(arrObj)
//let arr = dic.value(forKey: "TeacherName")as! NSArray
print(((dic.value(forKey: "teacherDetail") as! NSArray).object(at: 0) as! NSDictionary).value(forKey: "TeacherName") as! String)
// the todo object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
// print("The title is: " + todoTitle)
} catch {
print("error trying to convert data to JSON")
return
}
} task.resume()
}

How to save JSON data from a POST Request into dictionary with Swifty Json?

I was able to print the json data in console which looks like this
{
"created_at" : "2016-07-21 20:46:53",
"name" : "PB Admin",
"id" : 1,
"updated_at" : "2016-07-21 12:46:53",
"lname" : "Admin",
"access_lvl" : 1,
"email" : "admin#admin.com",
"fname" : "PB"
}
, but could not save it into a dictionary.
The method for POST request
private func makeHTTPPostRequest(path: String, body: NSDictionary) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
// Set the method to POST
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = "POST"
do {
// Set the POST body for the request
let jsonBody = try! NSJSONSerialization.dataWithJSONObject(body, options: [])
request.HTTPBody = jsonBody
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data!)
print(json)//print on console
//i need to get the json data from here, but for some reason it would skip
//this method
self.parseJSON(json)
})
task.resume()
} catch {
// Create your personal error
//onCompletion(nil, nil)
}
}
This method should save the json data into a dictionary
private func parseJSON(json: JSON) {
for(_, object) in json {
let createdAt = object["created_at"].stringValue
let name = object["name"].stringValue
let id = object["id"].stringValue
let updatedAt = object["updated_at"].stringValue
let lName = object["lname"].stringValue
let accessLvl = object["access_lvl"].stringValue
let email = object["email"].stringValue
let fname = object["fname"].stringValue
let obj = ["createdAt":createdAt, "name":name, "id":id, "updatedAt":updatedAt, "lName":lName, "accessLvl":accessLvl, "email":email, "fname":fname ]
objects.append(obj)//wherein objects is a string dictionary
}
}
Whenever I debug the code, objects dictionary is always null even if the whole processed has finished.
You can convert your JSON data to NSData so you can easly get yor data from NSData rather than JSON.
public class func jsonToNSData(json: AnyObject) -> NSData?{
return NSJSONSerialization.dataWithJSONObject(json, options: .allZeros, error: nil)
}
Then you can create a function that returns NSDictionary like this:
func parseJSON(data: NSData) -> NSDictionary{
var dic: NSDictionary!
do {
boardsDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
} catch let error as NSError {
print(error.localizedDescription)
print("Error could not parse JSON data, it's null maybe?!!")
}
//'\(jsonStr)'
return dic
}
Last One: Create your dictionary
let dic = parseJSON(jsonToNSData(YourJsonData)) as! NSDictionary
Hope it helps.
let jsonDictionary = try! NSJSONSerialization.JSONObjectWithData(data!,
options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

Resources