JSON解析 - > Swift | JSON写入中的顶级类型无效

I am trying to retrieve information from a PHP file using Swift. I have seen online that I should use JSON parsing (I think it's called). So I searched and found some information online leading me to the following code:

func dataOfJson(urlString: String) -> NSArray{
    let url = NSURL(string: urlString);
    if (url != nil)
    {
        let data = NSData(contentsOf: url as! URL);
        if (data != nil)
        {
            return try! JSONSerialization.data(withJSONObject: data as Any) as AnyObject! as! NSArray;
        }else{
            //return "Error -> Data is nil!";
            return try! JSONSerialization.data(withJSONObject: data as Any) as AnyObject! as! NSArray;
        }
    }else{
        return ["Error -> url is empty!"] as NSArray;
    }
}

I call the above function like so:print(dataOfJson(urlString: "some url/test.php"));

The URL I call has the following PHP code:

<?php   
header("Content-Type: application/json");
require "dbconnect.php";
global $connect;
$result = array();
$temp = array();

if ($connect){
    $fetch_data = mysqli_query($connect,"select * from dedi");

    while ( $row = $fetch_data->fetch_object() ){
        $temp = $row;
        array_push($result,$temp);
    }

    echo json_encode($result);
    return json_encode($result);
}
else{
    echo json_encode("Something went wrong");
    return json_encode("Something went wrong!");    
} 
mysqli_close(); ?>

Sadly, when I try and run the project, I get the following error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'

I have absolutely no idea how to fix it, and yes, I have searched online and found resembling problems with solutions, but I could not understand these and some of the fixes just didn't change anything...

The documentation of NSJSONSerialization states some requirements that the JSON from your PHP script probably doesn't always conform to:

An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.