I have been trying to get the below code to return an array of information that can use in a UIPickerView class "title for Rows. The code does not work, I do now that when I run the print script it does return a list of all the values from my JSON values. A sample of parsed JSON. I have been watching YouTube Videos and reading info about this for two evenings now. Any help would be great. Everything I find sends Parsed JSON results to a table view.
{
date = "2017-05-01";
"financial_institution" = "Your Neighbourhood C.U.";
"five_year" = "2.79";
"four_year" = "3.15";
key = 86;
"one_year" = "2.79";
"six_months" = 0;
"three_year" = "3.09";
"two_year" = "2.89";
"variable_rate" = 0;
}
)
func getJSONData()
{
let url = URL(string:"")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print("error")
}
else {
if let mydata = data {
do {
let myJson = try JSONSerialization.jsonObject(with: mydata, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJson)
var lenderName = myJson["financial_institution"]
for i in lenderName {
var lender = "financial_institution"
lender += "\(i)"
var lenderList = myJson[lender].string as String!
lenderNamesArray.append(lenderList)
}
}
catch {
// catch error
}
}
}
}
task.resume()
}
Related
I am using shopify iOS SDK(mobile-buy-sdk-ios) in react native to get login user's orders.
Here is my code,
let query = Storefront.buildQuery { $0
.customer(customerAccessToken: token) { $0
.orders(first: count, reverse: true) { $0
.edges { $0
.node { $0
.id()
.orderNumber()
.totalPrice()
.statusUrl()
.lineItems(first: 25){ $0
.edges{ $0
.node{ $0
.title()
.quantity()
.variant{ $0
.id()
.price()
.title()
.image{ $0
.originalSrc()
}
}
}
}
}
let task = self.client.queryGraphWith(query, cachePolicy: .networkOnly) { response, error in
error.debugUserPrint()
let userOrders = response.customer?.orders.edges[0].node;
let res = try! JSONSerialization.data(withJSONObject: userOrders)
completion([res])
}
And I am getting this response in userOrders variable
<QueryRoot: ["customer": {
orders = {
edges = (
{
node = {
id = "Z2lkOi8vc2hvcGlmeS9PcmRlci8yMjY2NTM3NzU0NzEwP2tleT0zNWFiYzBkMjRmMDk3MjZlYzgzYjkwZDVlZGI5YjM4MA==";
lineItems = {
edges = (
{
node = {
quantity = 1;
title = "Gift wrapping";
variant = {
id = "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC8xMjE3MzkzNjYyMzcwMg==";
image = {
originalSrc = "https://cdn.shopify.com/s/files/1/2331/3377/products/Gift_Boxes_11_22_2017_Standard_1024x1024_60d01a1c-f665-4c9e-b80b-f6fda9167de3.jpg?v=1521444032";
};
price = "10.00";
title = "Default Title";
};
};
}
);
};
orderNumber = 1040;
statusUrl = "23313377/orders/11f378e7df2731521429f377015d2ec2/authenticate?key=35abc0d24f09726ec83b90d5edb9b380";
totalPrice = "10.00";
};
}
);
};
}]>)
this formate, so try to parse this data to JSON object to pass data from iOS function to javascript function. I have tried
JSONSerialization.data(withJSONObject: userOrders)
but it is not working. I just want to parse this data to JSON. I have also tried many other ways but no luck.
Thanks.
They're a number of ways I can think of...
Alamofire if you have access to that query endpoint
Alamofire.request("http://feeds.news24.com/articles/Fin24/Tech/rss").responseJSON { json in
/// do what you want with your json
}
No endpoint, use SwiftyJSON
let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
//Now you got your value
}
I don't think there is straightforward way to get JSON, using mobile-buy-sdk. However you can convert response to JSON
if let data = try? JSONSerialization.data(withJSONObject: userOrders.fields, options: .prettyPrinted) {
print(String(data: data, encoding: .utf8))
}
So I am not sure how to make the quote update ones daily at the same time for all users not depending on the last time they opened the app? If I am not specific enough or anything let me know. Thanks:)
let tasks = URLSession.shared.dataTask(with: URL(string: "https://talaikis.com/api/quotes/random/")!) { (data, response, error) in
if error != nil {
print("error")
} else {
if let content = data {
do {
let Json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let data = Json as? [AnyHashable:Any] {
if let quote = data["quote"], let cat = data["cat"], let author = data["author"] as? String {
print(cat)
DispatchQueue.main.async {
self.myLabel.text = "\(quote)"
self.authorLabel.text = "\(author)"
}
}
}
} catch {
}
}
}
}
tasks.resume()
Here i had implemented pagination for the table view and items are loaded by using model class but here the loaded items are replacing with the new items and whenever it calls api it returns the new data and old data is overriding on it and displaying only 10 items at a time i am implementing it for first time can anyone help me how to resolve the issue ?
func listCategoryDownloadJsonWithURL(listUrl: String) {
let url = URL(string: listUrl)!
print(listUrl)
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil { print(error!); return }
do {
if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
self.listClassModel = ModelClass(dict: jsonObj as [String : AnyObject])
DispatchQueue.main.async {
guard let obj = self.listClassModel else { return }
let itemsCount = obj.items.count
print(itemsCount)
for i in 0..<itemsCount {
let customAttribute = obj.items[i].customAttribute
for j in 0..<customAttribute.count {
if customAttribute[j].attributeCode == "image" {
let baseUrl = "http://192.168.1.11/magento2/pub/media/catalog/product"
self.listCategoryImageArray.append(baseUrl + customAttribute[j].value)
print(self.listCategoryImageArray)
}
}
}
self.activityIndicator.stopAnimating()
self.activityIndicator.hidesWhenStopped = true
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.reloadData()
self.collectionView.isHidden = false
self.tableView.reloadData()
}
}
} catch {
print(error)
}
}
task.resume()
}
You are assigning your result data to model array, each time you call your API. This is the reason that your old data is getting replaced with new one. Rather than assigning, you should append the new data to your datasource array.
if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
self.listClassModel.append(contentsOf: ModelClass(dict: jsonObj as [String : AnyObject]))
Also make sure you initialize your array as an empty array first. (maybe in declaration or viewDidLoad) before calling API.
I have these JSON data.
(
{
email = "b#p.com.my";
login = ID001;
pw = 1234;
},
{
email = "p#d.com.my";
login = ID002;
pw = 12345;
}
)
Right now, I can only print myJSON value in x code output.
My question is, how to display each JSON into UILabel _email, _login, _pw?
Someone said that I need to store as variable and set into UILabel but i don't know how to do it. Appreciate if someone can help me on this matters.
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet var _email: UILabel!
#IBOutlet var _login: UILabel!
#IBOutlet var _pw: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://localhost/get.php")
let task = URLSession.shared.dataTask(with: url!) {
(data, response, error) in
if error != nil {
print("Error")
return
}
else {
if let content = data {
do {
let myJSON = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJSON)
}
catch {}
}
}
}
task.resume()
}
}
Thanks.
EDIT:
After the block where you print your myJSON, try this:
for eachItem in myJSON {
if let emailParsed = eachItem["email"] as? String {
print(emailParsed)
_email.text = emailParsed
}
}
This loop runs between all the dictionaries and
This solution could be helpful for you. Please go through it!
Hi Please try this one
for i..0 < myJson.count {
let object = myJson[i] as AnyObject
if let emailParsed = myJSON["email"] as? String {
_email.text = emailParsed
}
}
EDITED
for i..0 < myJson.count {
let object = myJson[i] as [String : AnyObject]
if let emailParsed = myJSON["email"] as? String {
_email.text = emailParsed
}
}
It's simple because your json object gives an array of dictionary so first you have to take first object from array and after that you can take the string passing the key
override func viewDidLoad()
{
super.viewDidLoad()
let url = URL(string: "http://localhost/get.php")
let task = URLSession.shared.dataTask(with: url!)
{
(data, response, error) in
if error != nil
{
print("Error")
return
}
else
{
if let content = data
{
do {
let myJSON = try JSONSerialization.jsonObject(with: content, options:JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
// print(myJSON)
for data in myJSON
{
let email = data.1["email"] as? String
_email.text = email
}
}
catch {}
}
}
}
task.resume()
}
}
For batter option you can use some predefined libraries like swiftyJSON. To get best result.
I am trying to access items parsed in JSON from the iTunes API using Swift 3.0, but I am struggling to access the objects after they have been parsed. The objects are being parsed in this format:
{
resultCount = 50;
results = (
{
artistId = 70936;
artistName = "Johnny Cash";
artistViewUrl = "https://itunes.apple.com/us/artist/johnny-cash/id70936?uo=4";
artworkUrl100 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/100x100bb.jpg";
artworkUrl30 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/30x30bb.jpg";
artworkUrl60 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/60x60bb.jpg";
collectionCensoredName = "The Essential Johnny Cash";
collectionExplicitness = notExplicit;
collectionId = 251001680;
collectionName = "The Essential Johnny Cash";
collectionPrice = "14.99";
collectionViewUrl = "https://itunes.apple.com/us/album/ring-of-fire/id251001680?i=251002253&uo=4";
country = USA;
currency = USD;
discCount = 2;
discNumber = 1;
isStreamable = 1;
kind = song;
previewUrl = "http://a1144.phobos.apple.com/us/r1000/070/Music/b3/99/be/mzi.qvkhtgfg.aac.p.m4a";
primaryGenreName = Country;
releaseDate = "2002-02-12T08:00:00Z";
trackCensoredName = "Ring of Fire";
trackCount = 18;
trackExplicitness = notExplicit;
trackId = 251002253;
trackName = "Ring of Fire";
trackNumber = 15;
trackPrice = "1.29";
trackTimeMillis = 155707;
trackViewUrl = "https://itunes.apple.com/us/album/ring-of-fire/id251001680?i=251002253&uo=4";
wrapperType = track;
},
I want to be able to access the information from all 50 results, such as the artistName, for instance. This is my parsing function attempting to get the artistName and add it to my NSDictionary, but it keeps returning that it can't unwrap the dictionary.
func parser() {
let enteredText:String = (tbxSearch.text?.replacingOccurrences(of: " ", with: "+"))!
let url = "https://itunes.apple.com/search?term=\(enteredText)"
print(url)
guard let urlRequest = URL(string: url) else
{
print("Error creating endpoint")
return
}
let request = URLRequest(url: urlRequest)
URLSession.shared.dataTask(with: request) {(data,response,error) in
do
{
guard let data = data else
{
return
}
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else
{
return
}
if let results = json["results"] as? NSDictionary
{
self.avObjects.avDict.setValue("Artist Name", forKey: results["artistName"] as! String)
print(self.avObjects.avDict)
}
else
{
print("Couldn't unwrap the dictionary.")
}
print(json)
}
catch let error as NSError
{
print(error.debugDescription)
}
}.resume()
}
It looks like results is an array of dictionaries, not just a dictionary.
Instead of this: if let results = json["results"] as? NSDictionary
try this: if let results = json["results"] as? NSArray
You could then map or iterate over each element in the array, extracting "artistName" from each one, for example.
results is an array of dictionaries, not a dictionary itself. Try changing this:
if let results = json["results"] as? NSDictionary
to:
if let results = json["results"] as? NSArray
and then iterating over results. Each element of results is a dictionary with attributes such as artistName.