LoginSignup
22
18

More than 5 years have passed since last update.

SwiftでjsonをphpへPOSTする

Posted at

ねらい

  • 他でswift+jsonのpostがなかった
  • 一番書かれているプログラムもswiftのバージョンが2系だったりphp側の処理がないので、今回は3系で記述しphpも #実行環境
  • swift3
  • Xcode:8.4 beta
  • macOS:Sierra 10.12.3
  • php:7.0.15
  • MAMP:4.1.1

Swift側

一番やりたかったことが書かれたコードがあったんですが、2系だったため、今回はこれを3系に書き直しています。

override func viewDidLoad() {
        super.viewDidLoad()

        let urlString = "http://localhost:8888/test/postTest.php"

        let request = NSMutableURLRequest(url: URL(string: urlString)!)

        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")



        let params:[String:Any] = [
            "foo": "bar",
            "baz":[
                "a": 1,
                "b": 2,
                "x": 3]
        ]

        do{
            request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)

            let task:URLSessionDataTask = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {(data,response,error) -> Void in
                let resultData = String(data: data!, encoding: .utf8)!
                print("result:\(resultData)")
                print("response:\(response)")

            })
            task.resume()
        }catch{
            print("Error:\(error)")
            return
        }
 }

コードの説明(適当なところ)

let urlString = "http://localhost:8888/test/postTest.php"

POST先のURIをここでい指定します。

let params:[String:Any] = [: , :]

ここで、jsonファイルを作ってます。
swiftだとDictionary型が良いみたい。

let resultData = String(data: data!, encoding: .utf8)!

ここで、サーバーでのファイル処理結果を表示します。

PHP

本当に簡単に。

<?php

//recieve json from swift code
$json = file_get_contents('php://input');
echo $json;
$data = json_encode($json);
echo $data;
?>

コードの説明(適当なところ)

file_get_contents('php://input')

file_get_contents
->ファイルの中身をすべて文字列に読み込む

なにやら、bodyにくっついてるjsonデータをそのまま読み込む際は、引数に'php://input'を指定するとのこと。

動作結果

Xcodeに次の結果が表示されます。

Kobito.QiwfRg.png

参考ページ

22
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
18