Swift Json连接失败.JSON对象正确


Swift Json connection failed. JSON object correct?

我在尝试将Json对象放入我的iOS应用程序时遇到了很多问题。我用我的MySQL数据库创建了一个Json文件,如下所示:

<?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);
?>

现在json对象看起来不错。plato.guru.ksz.ch/index.php将是对象。这些是我加载到数据库中的新闻文章,它们都有一个ID、标题、描述、类别、链接、媒体和来源,所有这些都只是字符串(ID除外)

现在,我尝试将这个Json文件放入我的iOS对象中,以在表单元格中显示每一篇文章。我遇到了问题,但我不太确定是Json文件本身还是我的iOS应用程序的连接。

这是swift文件:

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.
  }
}

我手动导入了SwiftyJSON文件,因为我无法让它与pod一起工作。现在我的Json文件是否不正确,或者为什么我在执行程序时收到这个错误:致命错误:展开可选值时意外发现nil(lldb)

谢谢你的帮助,我已经被困了好几天了。

您需要在字符串中添加http://或https://

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

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

您的Content-type就是text/html。设置为application/json

用途:

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

在您的php文件

我建议您使用try将JSON数据分配给变量JSON有很多关于API连接、接收JSON的教程。

// Parse JSON
// By the way, is your variable JSON a dictionary?
// Here:
let json = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary