【问题标题】:How to represent MySQL Bit Type in Swift 3如何在 Swift 3 中表示 MySQL 位类型
【发布时间】:2017-01-03 06:20:12
【问题描述】:

我当前的数据库由 Bit 类型的对象组成,用来表示一个布尔变量。

但是,当我尝试将这些数据从 MySQL 抓取到 Swift 3 时,它返回 Nil。我知道我的 PHP 文件工作正常,因为当我单独运行我的 PHP 代码时,它会打印出正确的值集。

PHP 文件

<?php
session_start();
$current_username = $_SESSION["username"];
$current_password = $_SESSION["password"];

// open database
$con = mysqli_connect("localhost","root","root","fridge_items");
$mysqli = new mysqli("localhost","root", "root", "fridge_items");

// Check connection
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    exit();
} 
//Getting the user_id 
$query_id = "SELECT id FROM user WHERE username='$current_username'";
$result_id = $mysqli->query($query_id);

/* associative array */
//Fetches the user id 
$row_id = $result_id->fetch_array(MYSQLI_ASSOC);
$user_id = $row_id["id"];

//Fetches the user id 
$sql = "SELECT * FROM items where user_id='$user_id'";

// Check if there are results
if ($result = mysqli_query($con, $sql)) {
    // If so, then create a results array and a temporary one
    // to hold the data
    $resultArray = array();
    $tempArray = array();

    // Loop through each row in the result set
    while($row = $result->fetch_object()) {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

//Close connections 
mysqli_close($con);
?>

当我注释掉状态变量时,它会打印出正确的值。所以我认为它返回 nil 因为 Bool 不是在 MySQL 中表示 Bit 类型的正确方法。我尝试了 Int、NSInteger,但它们都不起作用。所以我真的不确定什么类型实际代表状态(位类型)。 快速文件

/*
* Fetching items from database
*/
func fetchItems() -> Void {

    let url: String = "http://localhost/fridge_app/fetchItems.php" //this will be changed to the path where service.php lives

     //created NSURL
     let requestURL = NSURL(string: url)

     //creating NSMutableURLRequest
     let request = URLRequest(url: requestURL! as URL)

     //creating a task to send the post request
     let task = URLSession.shared.dataTask(with: request as URLRequest) {
         data, response, error in

          //exiting if there is some error
          if error != nil {
              print("error is \(error)")
              return;
          }

          // Grabbing the items 
          var jsonResult: NSMutableArray = NSMutableArray()
          do {
              jsonResult = try JSONSerialization.jsonObject(with: data!, options:JSONSerialization.ReadingOptions.mutableContainers) as! NSMutableArray

          } catch let error as NSError {
              print(error)
          }

          var jsonElement: NSDictionary = NSDictionary()
          let items: NSMutableArray = NSMutableArray()

          for i in 0 ... jsonResult.count-1
          {
              jsonElement = jsonResult[i] as! NSDictionary
              let item = itemModel()
              print(jsonElement["status"])

              //the following insures none of the JsonElement values are nil through optional binding
              if let name = jsonElement["name"] as? String,
                  let status = jsonElement["status"] as? Bool
                  /*let date_in = jsonElement["date_in"] as? NSDate,
                  let count = jsonElement["count"] as? NSInteger,
                  let image = jsonElement["image"] as? NSObjectFileImage,
                  let expiration_date = jsonElement["expiration_date"] as? NSDate,
                  let item_id = jsonElement["item_id"] as? NSInteger*/
                {
                    item.name = name
                    item.status = status
                    /*item.date_in = date_in
                    item.count = count
                    item.image = image
                    item.expiration_date = expiration_date
                    item.item_id = item_id*/
                }
                items.add(item)
                print(item)
            }
        }
        //executing the task
        task.resume()
    }

【问题讨论】:

  • PHP 代码正在从 DB 中读取,Swift 代码正在解析 JSON,它们是不等价的。您的问题可能来自 json 解释,而不是来自数据库中的 Bit 值。
  • 是的,我明白了,那么我应该如何表示 jsonElement["status"]
  • 那么请更新问题,目前的形式具有误导性
  • 关于jsonElement["status"],做一个print(type(of: jsonElement["status"]))看看它有什么类型。
  • 它打印为任何类型

标签: php json swift


【解决方案1】:

我找到了解决方案。我没有将状态转换为特定类型,而是将其设为 Any 类型。如下图所示。现在可以了

var status: Any!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    相关资源
    最近更新 更多