2017-03-25 85 views
0

我想從我的MYSQL數據庫中讀取一行並將其變成我的應用程序中的一個字符串數組。從MySQL數據庫導入iOS應用程序中的數據

我的PHP文件:

<?php 
$host = 'localhost'; 
$user = 'root'; 
$password = ''; 
$database = 'diplomarbeit_testdatenbank'; 

$db_link = mysqli_connect($host, $user, $password, $database); 

$sql = "SELECT Kategorie FROM Kategorien WHERE Anzeige = '1'"; 

$result = mysqli_query($db_link, $sql); 

$records = array(); 
$array = array(); 

while($row = mysqli_fetch_assoc($result)){ 

    $records['Kategorie'] = $row['Kategorie']; 

    array_push($array, $records); 
} 

echo json_encode($array); 

?> 

...給我,輸出:

[{ 「Kategorie」: 「外部對象」},{ 「Kategorie」: 「家」}, { 「Kategorie」: 「萊勒」},{ 「Kategorie」: 「Oeffnungszeiten」},{ 「Kategorie」: 「Orientierung」},{ 「Kategorie」: 「Schulleitung」}]

中的功能我應用程序(使用Xcode 8和Swift 3):

func get() 
{ 
    do{ 
     let dburl = URL(string: "http://127.0.0.1/index.php") 
     let dbdata = try Data(contentsOf: dburl!) 

     let json = try JSONSerialization.jsonObject(with: dbdata, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject] 

     if let arrJSON = json["Kategorie"] 
     { 
      for indexx in 0...arrJSON.count-1 
      { 
       let aObject = arrJSON[indexx] 
       TableArray.append(aObject as! String) 
      } 
     } 
    } 
    catch let error as NSError{ 
     print("Failed to load: \(error.localizedDescription)") 
    } 
} 

它不顯示任何錯誤或類似的東西。當我模擬它時,應用程序凍結在我嘗試序列化的那一行。

而顯而易見的問題是:這裏出了什麼問題?

回答

0

的問題是這一行:

let json = try JSONSerialization.jsonObject(with: dbdata, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject] 

你的數據是[String:Any]字典的數組。但你也鑄造[String:AnyObject]

更改該行:

let json = try JSONSerialization.jsonObject(with: dbdata, options: JSONSerialization.ReadingOptions.mutableContainers) as! [[String:Any]] 

當然,你將不得不修改後的數據解析代碼的其餘部分,以及因爲您將通過需要循環該數組從每個字典實例中獲取值。

相關問題