Display downloaded data from database in tableview - mysql

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)

Related

Swift - Process.Launch getting different results than calling the same command in Terminal

I'm trying to integrate a CLI into a macOS Swift app. Calling the command in Terminal results in valid json:
{
"title": "SiteName",
"version": 1,
...
But if I use the following code I get additional characters:
let process = Process()
let pipe = Pipe()
process.arguments = arguments
process.launchPath = "/usr/local/bin/op"
process.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
I've tried other variations, such as using process.Run instead of process.Launch. All give the same results:
{
[94m"title"[0m: [92m"SiteName"[0m,
[94m"version"[0m: [93m1[0m,
Apparently, I must have done something differently before, since process.Run is working for me now.
let process = Process()
let pipe = Pipe()
process.standardError = pipe
process.standardOutput = pipe
process.executableURL = URL(fileURLWithPath: "/usr/local/bin/op"
process.standardInput = nil
process.arguments = arguments
try process.run()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!

Parse JSON Data in Swift from API Call "Value of type 'Any?' has no subscripts"

I am trying to parse some JSON data returned from an API call. The path I want to navigate is media > faces > tags. When I navigate to media it works, but when I add faces i receive the "Value of type 'Any?' has no subscripts" error.
I know this has been covered before on Stackoverflow but I can't seem to find out what is wrong. Any help is appreciated!
let dictionary = try JSONSerialization.jsonObject(with: data!, options:.mutableContainers) as? [String:Any];
// print(dictionary!["media"]) //this line works
print(dictionary!["media"]["faces"]) // this line does not work
The API returned data looks something like this
Optional({
checksum = 44efb3256385bfe62425c5fde195a3352e814ff6d900058e47a07b2cd7654252;
duration = "00:00:00";
faces = (
{
angle = "1.2222";
"appearance_id" = 0;
"detection_score" = 1;
duration = "00:00:00";
"face_uuid" = "78338d20-9ced-11ea-b153-0cc47a6c4dbd";
height = "74.31999999999999";
"media_uuid" = "fec83ac3-de00-44f0-ad5b-e1e990a29a8c";
"person_id" = "";
points = (
{
name = "basic eye left";
type = 512;
x = "85.16";
y = "86.62";
},
You need to cast the value returned from dictionary!["media"] as another Dictionary to be able to do this. Try this:
if let data = data,
let dictionary = try JSONSerialization.jsonObject(with: data, options:.mutableContainers) as? [String: Any],
let media = dictionary["media"] as? [String: Any] {
print(media["faces"])
}

Printing json in swift after download/parse

I'm trying to get the JSON from a website and parse it before printing it.
I've got a class called "JSONImport", which should handle a JSON Import from a server and print it.
A second class should make the call to start the Import and print the content of the JSON.
The following code is what I have so far (I took it from another question Downloading and parsing json in swift)
So this is my "JSONImport.swift":
var data = NSMutableData();
func startConnection(){
let urlPath: String = "http://echo.jsontest.com/key/value";
let url: NSURL = NSURL(string: urlPath)!;
let request: NSURLRequest = NSURLRequest(URL: url);
let connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!;
connection.start();
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data);
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
// throwing an error on the line below (can't figure out where the error message is)
do{
let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary;
print(jsonResult);}
catch {
print("Something went wrong?");
}
}
Inside another class, I would like to print the JSON by:
JSONImport.startConnection();
Now I get an error, because swift wants me to add a parameter to the call, making it look like:
JSONImport.startConnection(<#T##JSONImport#>);
Does someone have an idea, what I should put in there as a parameter?
I am confused, as i didn't declare one.
Thank you all in advance!
Kind regards, Manuel
startConnection() is a instance method, so you need to instantiate an JSONImport to call it.
Only type methods can be used that way. So it's essentially asking for an instance of JSONImport.
Here is how you should do it
let importer = JSONImport()
importer.startConnection()
or by calling from the type method
let importer = JSONImport()
JSONImport.startConnection(importer)
You can read more about instance/type methods at this guide

How to parse the data from JSON iOS

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

Can you save json data without being archived

I want to save json data into a file without being archived. This way I can open the file and check if everything is okay
// valid json data
if NSJSONSerialization.isValidJSONObject(jsonData) {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths[0] as! String
let path = documentsDirectory.stringByAppendingPathComponent("test.json")
println(path) // if I open the file from finder, all the data is archived
// try 1: the jsonData is archived
if NSKeyedArchiver.archiveRootObject(jsonData, toFile: path) {
println("saved: true");
}
let stringTest = "asd"
stringTest.writeToFile(path, atomically: true, encoding: NSStringEncoding.allZeros, error: nil)
// the string is also archived
}
I also try
var jsonNSData = NSKeyedArchiver.archivedDataWithRootObject(jsonData)
var string = NSString(data: jsonNSData, encoding: NSUTF8StringEncoding)
println(string) // returns nil
You can do it by casting your JSON to NSDictionary and then just write it to user documents directory:
var someJsonAsDict: [String: AnyObject] = ["foo": "string", "bar": NSNumber(integer: 5)]
if let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as? [String],
let documentsDirectory = paths.first
{
let filePath = documentsDirectory.stringByAppendingPathComponent("myPlistFile")
let fileManager = NSFileManager.defaultManager()
//IMPORTANT - someJsonAsDict cannot have primite types(they must be boxed in Appropriate NSNumber, NSValue, etc)
(someJsonAsDict as NSDictionary).writeToFile(filePath, atomically: true)
//print path of simulator so you can read it from terminal
println("target path is \(filePath)")
}
If you happen to have Array as most outer object of JSON, just replace:
someJsonAsDict as NSDictionary
with appropriate array method:
someJsonAsDict as NSArray
All this will create plist file with the JSON. If you happen to need it in raw json style(as like txt) you can use plutil(installed with Xcode command line tools):
plutil -convert json myPlistFile.plist -o MyTxtFile.json
maybe you can use NSUserDefaults to archive value. like var save = NSUserdefaults.userdefaults()then var ValueSaved = save.setObject(stringTest, "StringTest") this is the easiest mode to archive a file.. but it doesn't archive in a file :\