gpt4 book ai didi

php - 使用swift发布到php脚本后如何在IOS中获取php回显响应

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

我想知道在 ios 应用程序中,如何在使用 swift 发布到 php 脚本后获得 php echo 响应

现在,当我在 iOS 应用程序中打印响应时,它会显示很多信息,例如状态代码、标题、内容类型、日期。但是我两个都不想要

我想要的只是 ios 应用程序可以返回 php 回显字符串 <?php echo 'You have successfully registered';?>

银行代码

    let myUrl = URL(string: "http://www.swiftdeveloperblog.com/http-post-example-script/");

var request = URLRequest(url:myUrl!)

request.httpMethod = "POST"// Compose a query string

let postString = "firstName=James&lastName=Bond";

request.httpBody = postString.data(using: String.Encoding.utf8);

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

if error != nil
{
print("error=\(error)")
return
}

// You can print out response object
print("response = \(response)")

//Let's convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

if let parseJSON = json {

// Now we can access value of First Name by its key
let firstNameValue = parseJSON["firstName"] as? String
print("firstNameValue: \(firstNameValue)")
}
} catch {
print(error)
}
}
task.resume()

PHP 代码

<?php echo 'You have successfully registered';?>

最佳答案

您的 PHP 代码将输出:

You have successfully registered

您的 Swift 代码仅打印整个响应对象(其中包含大量信息),然后您尝试将数据解析为 JSON 响应,但事实并非如此,因此它将失败。

您需要做的是访问响应数据(它将从 PHP 代码输出)并将其转换为字符串

if let data = data {
let string = String(data: data, encoding: String.Encoding.utf8)
print(string) //JSONSerialization
}

尝试将其放在错误处理之后的响应处理部分,这应该会显示您期望的响应。

关于php - 使用swift发布到php脚本后如何在IOS中获取php回显响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48073267/

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