Sascha
Sascha

Reputation: 95

Swift Json connection failed. JSON object correct?

I've been having a lot of problems while trying to get a Json object into my iOS application. I created a Json file out of my MysqlDB like this:

<?php
//open connection to mysql db
$connection = mysqli_connect("127.0.0.1","root","","FeedStuff") or die("Err$

//fetch table rows from mysql db
$sql = "select * from articles";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . my$

//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
    $emparray[] = $row;
}
echo json_encode($emparray);

//close the db connection
mysqli_close($connection);
?>

Now the json object seems to look good. plato.guru.ksz.ch/index.php would be the object. These are news articles that I load into my DB and they each have a ID, title, description, category, link, media and source, all of which are just strings ( except ID)

Now I try to get this Json file into my iOS object, to display each article in a table cell. I run into problems but i'm not quite sure if it may be the Json file itself or the connection of my iOS app.

This is the swift file:

import UIKit

class ViewController: UIViewController {

  override func viewDidLoad() {

    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let filePath = NSURL(string: "plato.guru.ksz.ch/index.php")
    let jsonData = NSData(contentsOfURL:filePath!)
    let json = JSON(data: (jsonData)!, options: NSJSONReadingOptions.AllowFragments, error: nil)

    print(json)
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
}

I imported the SwiftyJSON file manually because i wasn't able to get it working with the pods. Now is my Json file incorrect or why am i receiving this error when i execute the programm: fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

Thanks for your help, been stuck with this for days now.

Upvotes: 1

Views: 119

Answers (3)

Breek
Breek

Reputation: 1441

You need to add http:// or https:// to your string

let filePath = NSURL(string: "http://plato.guru.ksz.ch/index.php")

or

let filePath = NSURL(string: "https://plato.guru.ksz.ch/index.php")

Upvotes: 2

thinkswift
thinkswift

Reputation: 528

I propose you use try for assigning JSON data to variable json There are plenty of tutorials on API connections, receiving JSON.

// Parse JSON
// By the way, is your variable JSON a dictionary?
// Here:

let json = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

Upvotes: 0

Lou Franco
Lou Franco

Reputation: 89192

Your Content-type is text/html. Set it to application/json

Use:

 header('Content-Type: application/json');

In your php file

Upvotes: 1

Related Questions