duancunsu9209 2018-01-03 07:51
浏览 92
已采纳

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

I am wondering in the ios app, how to get php echo response after posting to the php script using swift

Now, when i print the response out in the ios app, it shows lots of info, such as status code,header,content type, date. But i want neither of them

All i want is the ios app can return the php echo string <?php echo 'You have successfully registered';?>

SWIFT CODE

    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 CODE

<?php echo 'You have successfully registered';?>
  • 写回答

1条回答 默认 最新

  • dpntq48842 2018-01-03 08:10
    关注

    Your PHP code will output:

    You have successfully registered

    Your Swift code just prints the whole response object (which contains alot of information), then your trying to parse the data as a JSON response, which it isn't, so it will fail.

    What you need to do is to access the response data (which will be be output from the PHP code) and covert it to a string

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

    Try putting this in your response handling section just after the error handling and this should show the response you expect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java代码写在记事本上后在cmd上运行时无报错但又没生成文件
  • ¥15 关于#python#的问题:在跑ldsc数据整理的时候一直抱这种错误,要么--out识别不了参数,要么--merge-alleles识别不了参数(操作系统-linux)
  • ¥15 PPOCRLabel
  • ¥15 混合键合键合机对准标识
  • ¥100 现在不懂的是如何将当前的相机中的照片,作为纹理贴图,映射到扫描出的模型上
  • ¥15 魔霸ROG7 pro,win11.息屏后会显示黑屏,如图,如何解决?(关键词-重新启动)
  • ¥15 有没有人知道这是哪里出了问题啊?要怎么改呀?
  • ¥200 C++表格文件处理-悬赏
  • ¥15 Windows Server2016本地登录失败
  • ¥15 复合卡卡号轨道写入芯片卡