現在、サーバー上のデータを受け取ってIphoneでクーポンを表示するアプリを作ろうと考えています。
参考書を元にサーバー上にphpファイル、画像ファイル、jsonファイルを設置するところまではできたのですが、Swift側からサーバー上のファイルを読み取る処理が全くうまくできず困っております。
実現したいこととしては、
"http://52.194.224.50/srv.php"に画像URLが含まれているjsonファイルを返すよう要求し、
サーバーから返ってきた
"http://52.194.224.50/data/coupon.json"のjsonファイルに含まれる画像URLを元に、
"http://52.194.224.50/data/image/coupon/noimage.png"の画像を
アプリで表示させるという処理です。
申し訳ありませんがご助言をお願い致します。
※追記
なんとかjsonファイルを取得することはできたので、
その中に含まれるURLを元に、サーバーの画像を取得したいです......
Swift
1import UIKit 2 3class ViewController: UIViewController { 4 5 @IBOutlet weak var image1: UIImageView! 6//サーバーから返ってきたURL情報を元に、画像を表示したい 7 8 override func viewDidLoad() { 9 super.viewDidLoad() 10 11 let postString = "command=getCoupon" 12 13 var request = URLRequest(url: URL(string: "http://52.194.224.50/srv.php")!) 14 request.httpMethod = "POST" 15 request.httpBody = postString.data(using: .utf8) 16 17 let task = URLSession.shared.dataTask(with: request, completionHandler: { 18 (data, response, error) in 19 20 if error != nil {return } 21 22 do { 23 let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) 24 let top = json as! NSArray 25 for roop in top { 26 let next = roop as! NSDictionary 27 print(next["imageUrl"] as! String) 28//サーバーから返ってきた"imageUrl"を元に、サーバーから画像を取得したい 29 } 30 } catch { 31 print(error) 32 } 33 34 }) 35 task.resume() 36 } 37} 38
PHP
1<?php 2$command = $_POST["command"]; 3 4if(strcmp($command, "getInformation") == 0) { 5 getInformation(); 6} else if(strcmp($command, "getCoupon") == 0) { 7 getCoupon(); 8} else { 9 echo(""); 10} 11 12function getInformation() { 13 echoFileData("data/information.json", "[]"); 14} 15function getCoupon() { 16 echoFileData("data/coupon.json", "[]"); 17} 18 19function echoFileData($fileName, $defaultString) { 20 21 if (file_exists($fileName)) { 22 $fileData = file_get_contents($fileName); 23 if ($fileData != false) { 24 echo($fileData); 25 return; 26 } 27 } 28 echo($defaultString); 29} 30?>
Json
1{ 2 "id":"1", 3 "date":"", 4 "imageUrl":"http://52.194.224.50/data/image/coupon/noimage.png", 5 "title":"サンプル", 6 "body":"サンプル", 7 "interval":"サンプル", 8 "condition":"サンプル" 9}
回答1件
あなたの回答
tips
プレビュー