How to append the data from the JSON - ios

How to append the data ?
my api as:-
[
{
"Name": "Vegetables",
"PictureModel": {
"ImageUrl": "http://example.jpeg"
}
},
{
"Name": "Fruits",
"PictureModel": {
"ImageUrl": "http://example1.jpeg"
}
}
]
for fetching the data from json
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! Array<[String:Any]>
print(json)
let type = json[0]
let name = type["Name"] as! String
let PictureModel = type["PictureModel"] as! [String:Any]
print(PictureModel)
let nameofimage = PictureModel["ImageUrl"] as! String
print(nameofimage)
self.fetchedHome.append(Categories(name: name, images: nameofimage))
self.tableview.reloadData()
} catch {
print(error)
}
}
}.resume()
And i got the output in the tableview .In tableview i got first data as name-vegetable and image in UIImageview.
.But second data not display .So how to append ? how to give for loop and append

Use this code you will get one by one object in For loop:-
if let data = json as? NSArray {
for data in data {
if let data = data as? [String: AnyObject] {
//Here you will get data
print("Name", data["Name"])
}
}
}

Are you getting JSON correctly in print(json)?
If yes, then you should try looping on "json" as follows :-
for (var keyAttr in json) {
let dataRow = json[keyAttr]
}
Inside the dataRow you can get "Name" and "PictureModel".
I am hoping that it should work.
All the best.

let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! Array<[String:Any]>
if let data = json as? [String:Any] {
for data in data {
let name = data["Name"] as! String
let PictureModel = data["PictureModel"] as! [String:Any]
print(PictureModel)
let nameofimage = PictureModel["ImageUrl"] as! String
print(nameofimage)
self.fetchedHome.append(Categories(name: name, images: nameofimage))
}
}
self.tableview.reloadData()
} catch {
print(error)
}
}
}.resume()

Related

Getting Cell Count after network operation

I am trying to get the collectionViewCell count from the network request but the value turns out to be always 0 (to which I initialised the count variable) I want the view to load the cells after I get it's count from the get request.What is it I'm doing wrong I have written this code after super.viewDidLoad().
DispatchQueue.global(qos:.background).async {
let token = "---------------------------"
let url = URL(string: "https:----------home.json?token="+token)!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
// print(String(data: data, encoding: .utf8)!)
let jsonWithObjectRoot = try? JSONSerialization.jsonObject(with: data, options: [])
// print(json!)
if let dictionary = jsonWithObjectRoot as? [String: Any] {
if let data = dictionary["data"] as? [String:Any]{
if let posts = data["posts"] as? [Any]{
count = posts.count
//print(count) //the value here is 2
for object in posts{
if let contentString = object as? [String: Any] {
print(contentString["title"] as! String)
// print(contentString["entered"]as! String)
}
}
}
}
}
}
task.resume()
/* end Request */
DispatchQueue.main.async{
self.collectionView.reloadData()
self.collectionView.collectionViewLayout.invalidateLayout()
}
}
Classic async case. You network calls are async, so your reload should happen inside the completion of the network call.
DispatchQueue.global(qos:.background).async {
let token = "---------------------------"
let url = URL(string: "https:----------home.json?token="+token)!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
// print(String(data: data, encoding: .utf8)!)
let jsonWithObjectRoot = try? JSONSerialization.jsonObject(with: data, options: [])
// print(json!)
if let dictionary = jsonWithObjectRoot as? [String: Any] {
if let data = dictionary["data"] as? [String:Any]{
if let posts = data["posts"] as? [Any]{
count = posts.count
//print(count) //the value here is 2
DispatchQueue.main.async{
self.collectionView.reloadData()
self.collectionView.collectionViewLayout.invalidateLayout()
}
for object in posts {
if let contentString = object as? [String: Any] {
print(contentString["title"] as! String)
// print(contentString["entered"]as! String)
}
}
}
}
}
}
task.resume()
/* end Request */
}
You have to reload after getting data from the network
count = posts.count
//print(count) //the value here is 2
DispatchQueue.main.async{
self.collectionView.reloadData()
}

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.

Passing data from JSON to table view cell in Swift 3

I'm trying to pass data from a JSON response to a table view cell. I'm having problems with capturing the response values that I'm extracting in URLSession.shared.dataTask.
func callYouTubeAPIToGetAllVideos() {
let url = URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=XYZ&maxResults=50&order=date&key=ABC")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error!)
} else {
if let usableData = data {
let json = try? JSONSerialization.jsonObject(with: usableData, options: [])
if let dictionary = json as? [String: Any?] {
if let array = dictionary["items"] as? [Any] {
for object in array {
if let objectAsDictionary = object as? [String: Any?] {
if let objectWithKindAndVideoId = objectAsDictionary["id"] as? [String: String] {
if let videoId = objectWithKindAndVideoId["videoId"] {
//pass data to table cell
}
}
if let snippet = objectAsDictionary["snippet"] as? [String: Any] {
if let description = snippet["description"] {
//pass data to table cell
}
}
}
}
}
}
}
}
}
task.resume()
}
I tried appending the values to an instance variable but it didn't work.
Sorry about the messy code, this is my 1st time working with JSON in Swift.
First of all never declare a received JSON dictionary as [String:Any?]. A received dictionary value can't be nil.
Declare a custom struct Video.
struct Video {
let videoId : String
let description : String
}
Declare a data source array.
var videos = [Video]()
Parse the JSON into the array and reload the table view on the main thread.
func callYouTubeAPIToGetAllVideos() {
let url = URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=XYZ&maxResults=50&order=date&key=ABC")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error!)
} else {
do {
if let dictionary = try JSONSerialization.jsonObject(with: data!) as? [String: Any],
let array = dictionary["items"] as? [[String: Any]] {
for object in array {
if let objectWithKindAndVideoId = object["id"] as? [String: String],
let snippet = object["snippet"] as? [String: Any] {
let videoId = objectWithKindAndVideoId["videoId"] ?? ""
let description = snippet["description"] as? String ?? ""
let video = Video(videoId: videoId, description: description)
self.videos.append(video)
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
} catch {
print(error)
}
}
}
task.resume()
}
In cellForRow assign the values to the text properties
let video = videos[indexPath.row]
cell.textLabel!.text = video.videoId
cell.detailTextLabel?.text = video.description

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 access array inside json object in swift

Can't access json object which is array inside json object
i want to access data from json object which have array inside array
and that json file is also uploaded
so pls can anyone check and help me how to get "weather.description"
data
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("some error occured")
} else {
if let urlContent = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
let newValue = jsonResult as! NSDictionary
print(jsonResult)
let name = newValue["name"]
//Here i am getting name as variable value
//this is not working
let description = newValue["weather"]??[0]["description"]
//this is not working
let description = newValue["weather"]!![0]["description"]
print()
}catch {
print("JSON Preocessing failed")
}
}
}
}
task.resume()
}
I have edited your code a bit, and added a few comments. Basiclly, lets check for the types of your response structure, and get the desired value.
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("some error occured")
} else {
if let urlContent = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
// I would not recommend to use NSDictionary, try using Swift types instead
guard let newValue = jsonResult as? [String: Any] else {
print("invalid format")
return
}
// Check for the weather parameter as an array of dictionaries and than excess the first array's description
if let weather = newValue["weather"] as? [[String: Any]], let description = weather.first?["description"] as? String {
print(description)
}
}catch {
print("JSON Preocessing failed")
}
}
}
}
task.resume()

Resources