gpt4 book ai didi

php - 如何在 Swift 中从 PHP 返回 JSON?

转载 作者:行者123 更新时间:2023-11-28 15:27:28 25 4
gpt4 key购买 nike

我正在尝试从 PHP/PDO 返回 json,但我在 Swift 中遇到此错误。

Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}

这是 PHP 文件。

//*FUNCTION TO GET CARD FROM SEARCH WORD CALLED FROM GetCards.php   
public function getAllCards($word) {

//Connect to db using the PDO not PHP
$db = new PDO('mysql:host=localhost;dbname=xxxx', 'xxxx', 'xxxxx');

//Here we prepare the SELECT statement from the search word place holder :word
$sql = $db->prepare('SELECT * FROM carddbtable WHERE businessNameDB=:word OR lastNameDB=:word OR firstKeywordDB=:word OR secondKeywordDB=:word OR thirdKeywordDB=:word OR fourthKeywordDB=:word OR fithKeywordDB=:word');

//We execute the $sql with the search word variable"$word"
$sql->execute([':word' => $word]);

//Looping through the results
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {

//Print to screen
// echo json_encode($row). "<br>"."<br>";

//Store all return rows in $returnArray
$returnArray[] = $row;
}

//Feedback results
return $returnArray;

}

这是 Swift。

    //Search and retrieve card / users
func doSearch (word : String) {

//Search word from searchKeyWordVar
let word = "TODAY"

// URL path to GetCards.php
let url = NSURL(string: "http://www.xxxxxxx.com/xxx/xx/GetCards.php")

//Create URL request
let request = NSMutableURLRequest(url: url! as URL)

//Method to pass info to GetCards.php
request.httpMethod = "POST"

//body that passing info to php
// let body = "word=\(word)"
let body = "TODAY" //This is hard coded for testing

//convert string to utf8 for all languages
request.httpBody = body.data(using: String.Encoding.utf8)


//Launch session
URLSession.shared.dataTask(with: request as URLRequest) { (Data, response, error) in


//Get main Queue
DispatchQueue.main.async(execute: {

if error == nil {

do {
// declare json var to store $returnArray inf we got from GetCards.php
let json = try JSONSerialization.jsonObject(with: Data!, options: .mutableContainers) as? NSDictionary


// delcare new secure var to store json
guard let parseJSON = json else {
print("Error while parsing")
return
}

// declare new secure var to store $returnArray["users"]
guard let parseUSERS = parseJSON["users"] else {
print(parseJSON["message"] ?? [NSDictionary]())
return
}

} catch {
print(error)
}


} else {
print(error as Any)
}


})

}.resume()


}

Agin 快速错误是Error Domain=NSCocoaErrorDomain Code=3840 “最后是垃圾。” UserInfo={NSDebugDescription=最后是垃圾。}

我只是没有看到它。当我从网页运行测试时,我得到如下所示的 json。

{"users":[{"idDB":"383","addressNotsDB":"\n","alternateNameDB":"","alternateNumberDB":"","businessMainCategoryDB":"News","businessNameDB":"TODAY"}]}

应用程序调用 GetCards.php 这调用 DBopperation.php 这有一个名为 getAllCards($word) 的 public_function

这是 GetCards.php

//STEP: 1 Make connection to DB
//Including the db operation file for connection to DB
$cardConnect = require_once 'DbOperation.php';

//Checking if there is a connection to DB
if ($cardConnect) {
$returnArray1['Connected to DB'] = '200';
} else {
$returnArray1['Did not connect ot DB'] = '400';
}
//echo json_encode($returnArray1). "<br>"."<br>";


//STEP: 2 Connecting to Public Function
//Connecting the DbOperation.php file public fuction getAllCards to the variable $card
$card = new DbOperation();

//If connected
if ($card) {

//Checking connection to the DbOperation.php
$returnArray2['Connected to GetCards.php'] = '200';
} else {
$returnArray2['Could not connect to GetCards'] = '400';
}
//echo json_encode($returnArray2). "<br>"."<br>";


//STEP: 3 Running the search
//Creating a varable to hold the search word and setting it to null
$word = null;

//Getting to search word from the app
if (!empty($_REQUEST["word"])) {
$word = htmlentities($_REQUEST["word"]);
}
// STEP 4. Access searching func and retrieve data from server
$users = $card->getAllCards($word);

if (!empty($users)) {
$returnArray3["users"] = $users;
} else {
$returnArray3["message"] = 'Could not find records in GetCards';
}


// STEP 4. Close connection
$card->disconnect();

// STEP 5. Pass information back as json to user
echo json_encode($returnArray);

最佳答案

首先,您的问题似乎是服务器发送的数据:

echo json_encode($row). "<br>"."<br>";

为什么最后是垃圾?您应该发回 json,为什么要添加错误的 html 标签?

echo json_encode($row);

其次,为什么要从函数打印?

您定义您的函数,对于它获取的每一行,将打印一个 JSON 对象。在发布的示例中,您似乎只有一行,超过一行将失败,因为 {}{} 不是有效的 JSON 对象。

改成这样:

public function getAllCards($word) {

...

//Looping through the results
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {

//Store all return rows in $returnArray
$returnArray[] = $row;
}

//Feedback results
return $returnArray;
}

然后你的调用者应该打印它:

$arrayOfResults = getAllCards();
echo json_encode( $arrayOfResults );

关于php - 如何在 Swift 中从 PHP 返回 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45046246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com