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

标签 php ios swift

我想知道在 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/

相关文章:

ios - 替换出现的字符串模式

javascript - Php 不能与 ajax 一起工作

php - Zend Framework 中以 API 为中心的开发

html - iOS:带有 iframe 的页面不会在 WKWebView 中滚动

ios - 如何解决应用程序验证 "The app references non-public selectors in Payload/MyApp.app/MyApp: _setAlwaysRunsAtForegroundPriority:"?

ios - 在 Swift 中获取两个 NSDate() 实例之间的时间间隔时遇到问题

swift - Vapor 2,一对多关系

php - 每次页面刷新后 session 不保留值

php - 处理试图破解网站的最佳方法

iphone - Xcode、 Objective-C 、IOS。线程 1 : Program received signal: "SIGABRT". 我做错了什么