How to parse the data from JSON iOS - json

I am building an app in iOS using SWIFT and i have also been using swiftyJSON to make this project a little easier.
func parseJSON(){
let path : String = NSBundle.mainBundle().pathForResource("jsonFile", ofType: "json") as String!
let url : String = "http://www.thegoodsite.org/attend/api.php?users_id=1"
let nsurly = NSURL(string: url)
let jsonData = NSData(contentsOfURL: nsurly!) as NSData!
let readableJSON = JSON(data: jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil)
var Name = readableJSON
numberOfRows = readableJSON["People"].count //Ignore this for the question
NSLog("\(Name)")
}
I am loading this data from a url so if going to include a picuture of the data im getting back in the console.
CLICK THIS LINK TO SEE IMAGE OF WHAT THE CONSOLE SAYS
So what code do i need to add to get the email to come out as text.
var Name = readableJSON ["users","email"]
However when I do that to the code I seems not to get any data at all.
How can I edit this code to get the email like I want?

let users = readableJSON["users"]
let user = users[0] // get info of the first user, you should check more here
let email = user["email"]
Or (as #nhgrif's cmt):
if let users = readableJSON["users"], user = users.first, email = user["email"]

I play the code,then i found the result of Json if Dictionary, so use the var Name = readableJSON["users"]!![0]["email"]

Related

Get HTML from query url (index.php?[arguments] ) Swift 3 ios

I'm working on Ios and Swift 3 and I want to parse HTML Code.
Until now Hpple did the trick for me using this code:
func parse_Html_Text(url:String)
{
let data = NSData(contentsOf: URL(string: url)!)
let doc = TFHpple(htmlData: data! as Data!)
}
But when I'm trying to get html code from a query url (like this one: link), then my app crashes and I get Thread1: EXC_BAD_INSTRUCTION error in this line:
let doc = TFHpple(htmlData: data! as Data!)
I also tried Alamofire's request method but I didnt manage to make it work
I'm stucked two days with this so any help will be appreciated.
Thank you in advance!
I noticed that you use Swift 3. Probably the library expects an NSData object but I would suggest to write your function like the following:
func parse_Html_Text(url: String) {
if let safeUrl = URL(string: url) {
let data = try? Data(contentsOf: safeUrl)
let doc = TFHpple(htmlData: data as? NSData)
}
}
In this case keep in mind that we are not handling possible error from the data setter.

Swift/Firebase Converting the snapshots (JSON) into Excel

does anyone here knows of a good method to convert Firebase data into excel format? Ideally I would like to do this by function call, such that I can pull the JSON database from Firebase and convert them into excel format.
Taking my JSON from Firebase as an example:
Snap (-KQc-qqY3qc6ZQgQQ4EF) {
DOB = "01/09/2016";
purpose = "No purpose";
name = "Adam";
timeOfVisit = 1803;
userID = LV6aANvLfAcTXTDpsZr5R4viUnE2;
}
When a user taps a 'export to excel' button, I would like to grab the JSON file from Firebase and convert it to excel file. Subsequently I would like to send this file to the user via email.
#IBAction func exportToExcel(sender: AnyObject) {
let dataSnapshot: FIRDataSnapshot! = self.database[indexPath.row]
let databaseValues = dataSnapshot.value as! Dictionary< String, AnyObject>
let name = databaseValues["name"] as! String!
let time = databaseValues["timeOfVisit"] as! Int!
let DOB = databaseValues["DOB"] as! String!
let purpose = databaseValues["purpose"] as! String!
// parse above variables into individual rows in excel file
}

How to convert a JSON string into a normal string in Swift?

I use SwiftyJSON to get data in JSON format from an API. This data is stored into a variable which I want to convert into a String.
I have the following:
func parseJSON() {
let path2 = NSURL(string: "https://pokeapi.co/api/v2/pokemon/5")
let jsonData2 = NSData(contentsOfURL: path2!) as NSData!
let readableJSON2 = JSON(data: jsonData2, options: NSJSONReadingOptions.MutableContainers, error: nil)
numberOfRows = readableJSON2["name"].count //maybe hardcode this in the future?
let id = readableJSON2["id"]
NSLog("\(id)")
let name = readableJSON2["name"]
NSLog("\(name)")
let weight = readableJSON2["weight"]
NSLog("\(weight)")
let height = readableJSON2["height"]
NSLog("\(height)")
idArray.append(id)
}
Note that the idArray is a String array:
var idArray = [String]()
The NSLog("(id)") returns a 5. I want this 5 to be a string, but I don't know how. I tried the following:
var id = readableJSON2["id"].string as String!
but this results into a nil..
Any ideas?
You need to typecast the value rather than force unwrap it as a String, as so:
var id = String(readableJSON2["id"])
Let me know if that works.

Trying to fetch image URL in Swift using Google Image API

I'm trying to use the google image API with JSON (https://developers.google.com/image-search/v1/jsondevguide) to get the URL of the first image that shows when searching something. This is what I have:
let placeName = "New York"
func getImage() {
let url = NSURL(string: "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=\(placeName)")
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()){ (response, go, error) -> Void in
let go = NSJSONSerialization.JSONObjectWithData(go, options: NSJSONReadingOptions.AllowFragments, error: nil) as [String:AnyObject]
let responseData = go["responseData"] as [String:AnyObject]
// let results = responseData["results"] as [String:AnyObject]
// let imageURL = results["unescapedUrl"] as String
println(responseData)
}
}
The responseData part is as far as I can go (that then returns everything), but trying to go one level deeper (to "results") will crash it.
You declare results as a dictionary but your linked Google page shows an example where results is an array of dictionaries.
You can do this instead:
let results = responseData["results"] as [[String:String]]
let firstObject = results[0]
let firstURL = firstObject["unescapedUrl"]

Display downloaded data from database in tableview

I created a database with PHPMyAdmin. Then I uploaded a php file to a web service to load the database. Now I have the url of the php file, which load the database.
This code works fine to load the database into the app:
func retrieveData() {
let url:NSURL = NSURL(string: phpURL)!
var data:NSData = NSData(contentsOfURL: url)!
json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as NSMutableArray
for (var i:NSInteger = 0; i < json.count; i = i + 1) {
newPlatz = json.objectAtIndex(i).objectForKey("Platz") as? NSString
newVerein = json.objectAtIndex(i).objectForKey("Verein") as? NSString
newPunkte = json.objectAtIndex(i).objectForKey("Punkte") as? NSString
newDifferenz = json.objectAtIndex(i).objectForKey("Differenz") as? NSString
newSpiele = json.objectAtIndex(i).objectForKey("Spiele") as? NSString
var myBundesliga:Bundesliga = Bundesliga.alloc()
myBundesliga.initWithBundesligaID(newPlatz, nVerein: newVerein, nSpiele: newSpiele, nDifferenz: newDifferenz, nPunkte: newPunkte)
bundesligaArray = NSMutableArray.alloc()
//bundesligaArray.addObject(myBundesliga)
println("\(newPlatz!);\(newVerein!);\(newPunkte!);\(newDifferenz!);\(newSpiele!)")
}
}
The output in the console:
1;FC Bayern München;17;13;7
2;TSG Hoffenheim;13;5;7
3;Bor. Moenchengladbach;13;5;7
4;Bayer 04 Leverkusen;12;2;7
5;1. FSV Mainz 05;11;4;7
and so on...
It works perfectly. But now i do not know how to display the data in my tableview. As you can see in the code above, the line code behind the two slashes do not work perfectly. Always when i run the app there is a 'Thread 1: breakpoint 1.1' error in this line:
bundesligaArray.addObject(myBundesliga)
I do not know why. Can somebody help me?
The problem is how you're instantiating your objects. You have:
bundesligaArray = NSMutableArray.alloc()
That should be:
bundesligaArray = NSMutableArray()
And, of course, you want to define that before your for loop, not inside it.
Or, if you wanted to use a Swift array, you'd define bundesligaArray as:
var bundesligaArray: [Bundesliga]?
And you'd instantiate it with
bundesligaArray = [Bundesliga]()
And you'd add objects to it with
bundesligaArray?.append(myBundesliga)