JSONDecoderがうまく行かない

override func viewDidLoad() {
        super.viewDidLoad()
        let listUrl = "http://hpscript.com/swift/index.php"
        do {
            guard let url = URL(string: listUrl) else { return }
            URLSession.shared.dataTask(with: url){(data, response, error) in
                if error != nil {
                    print(error!.localizedDescription)
                }
                
                guard let data = data else { return }
                let json = try? JSONDecoder().decode([JsonSample].self, from: data)
                }.resume()
            
        } catch{
            
        }
        self.label.text = json[0].name
        // Do any additional setup after loading the view, typically from a nib.
    }

なぜだ!!!!?

swift4でmysqlからfetchしたjsonを取得する

まず、mysqlからpdoでselectして、jsonにする。

$response = array();

$dsn = "mysql:dbname=app;host=";
$user = "";
$password = "";
try {
  $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e){
  print('connection failed:'.$e->getMessage());
}


$sql = "select * from swift";
$stmt = $dbh->query($sql);
$i = 0;
foreach($stmt as $value){
	$response[$i]['name'] = $value['name'];
	$response[$i]['member'] = $value['member'];
	$i++;
}


	
echo json_encode($response);

echo "finish";

勿論ここまではOK

問題は、x-codeで取得して、どう表示するか。

swift4からmysqlにinsertする

uiview.controller

let URL_SAVE_BOY = "hoge"
    
    @IBOutlet weak var NameFeild: UITextField!
    @IBOutlet weak var oldFeild: UITextField!
    
    @IBAction func saveBtn(_ sender: Any) {
        let requestURL = NSURL(string: URL_SAVE_BOY)
        let request = NSMutableURLRequest(url: requestURL! as URL)
        
        request.httpMethod = "POST"
        
        let teamName = NameFeild.text
        let memberOld = oldFeild.text
        
        let postParameters = "name="+teamName!+"&old="+memberOld!;
        
        request.httpBody = postParameters.data(using: String.Encoding.utf8)
        
        let task = URLSession.shared.dataTask(with: request as URLRequest){
            data, response, error in
            
            if error != nil {
                print("error is \(error)")
                return;
            }
            
            do {
                let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                
                if let parseJSON = myJSON {
                    var msg : String!
                    msg = parseJSON["message"] as! String?
                    print(msg)
                }
            } catch {
                print(error)
            }
        }
        task.resume()
    }

php側

$response = array();

if($_SERVER['REQUEST_METHOD'] == 'POST'){
	$teamName = $_POST['name'];
	$member = $_POST['old'];
}

$dsn = "mysql:dbname=db;host=hostname";
$user = "username";
$password = "pwd";
try {
  $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e){
  print('connection failed:'.$e->getMessage());
}


$sql = "insert into swift (name, member) VALUES (:name, :member)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':name', $teamName, PDO::PARAM_STR);
$stmt->bindValue(':member', $member, PDO::PARAM_INT);

$stmt->execute();

	$response['api'] = "succeeded";
	$response['member'] = $member . " years old!";
	echo json_encode($response);

echo "finish";

エミュレーターでyyyy, 55と入れます。

DB側
今回は,phpadmin

ちゃんと入っています。

次は、
1.mysqlからfetch。
2.配列をtable viewから表示
3.ec2から接続する
4.androidのDB接続
5.photoshopのエレメントをxcodeに乗せてく
6.app構築
7.app storeに申請
ってところか。
う〜、、、やること思ってたより多い。

table view

table viewでインド人に作ってもらった。

import UIKit

class CategoryListVC: UIViewController,UITableViewDataSource,UITableViewDelegate {

    //MARK:- IBOutlets
    @IBOutlet var tblCategoryList: UITableView!
    
    //MARK:- Variables
    var arrCategoryListData = NSMutableArray()
   
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.setupUI()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK:- SetUp UI
    func setupUI() -> Void {
        
        self.tblCategoryList.delegate = self
        self.tblCategoryList.dataSource = self
        
        self.arrCategoryListData = [["Name":"Motors"],["Name":"Fashion"],["Name":"Electronics"],["Name":"Collectibles & Art"],["Name":"Home & Garden"],["Name":"Sporting Goods"],["Name":"Toys & Hobbies"],["Name":"Bussiness & Industrial"],["Name":"Music"]]
        self.tblCategoryList.reloadData()
        
    }
    
    
    //MARK:- UITableView Related Methods
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.arrCategoryListData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewFOrCategoryListing", for: indexPath) as! TableViewFOrCategoryListing
        
        guard let dictCell = self.arrCategoryListData.object(at: indexPath.row) as? NSDictionary else {
            return cell
        }
        
        if let price = dictCell.value(forKey: "Name") {
            cell.lblCategoryName.text = String(describing: price)
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let dictCell = self.arrCategoryListData.object(at: indexPath.row) as? NSDictionary else {
            return
        }
        
        if let objView = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as? ViewController {
            
            objView.dictForCategoryDetails = dictCell
            self.navigationController?.pushViewController(objView, animated: true)
        }
        
    }
    

}

class TableViewFOrCategoryListing: UITableViewCell {
    
    @IBOutlet var lblCategoryName: UILabel!
    
}

やべー、俺も早く頑張らないと。。

ec2でgit

$ git version
git version 2.14.4

共有リポジトリをつくる。
bareリポジトリは、ワーキングコピーを持たないリポジトリ
sharedオプションをつけないと,ファイルパーミッションが無くてpushできなくなってしまう

mkdir test.git
cd test.git
git --bare init --shared
git clone ../git/test.git

git remote add origin
git push -u origin master

$ git push origin master
The authenticity of host ‘()’ can’t be established.
何!?

s3から画像をダウンロードする

require_once('vendor/autoload.php');

$s3client = new Aws\S3\S3Client([
		'credentials' => [
				'key' => '',
				'secret' => ''
		],
		'region' => 'ap-northeast-1',
		'version' => 'latest',
]);

$result = $s3client->getObject([
		'Bucket' => 'capital-technology',
		'Key' => 'img.jpeg',
]);

echo $result['ContentLength'];

OK!

次は、vagrantからec2にgitでpush, commitをしたい。

phpでlocalからS3に画像をアップロードする

aws sdk for php v3を使う。autoload.phpで良い。

<?php

require_once('vendor/autoload.php');

$s3client = new Aws\S3\S3Client(&#91;
		'credentials' => [
				'key' => '',
				'secret' => ''
		],
		'region' => 'ap-northeast-1',
		'version' => 'latest',
]);

$result = $s3client->putObject([
		'Bucket' => 'capital-technology',
		'Key' => 'img.jpeg',
		'SourceFile' => 'aaa.jpeg',
		'ContentType' => mime_content_type('aaa.jpeg'),
]);

アップロードはできたが、公開するとしないと、アクセスできない。
更に、ストレージクラスもスタンダード。ここらへんをphp側で操作できるようにしたい。

ACLで’public-read’と指定すると公開指定ができる。

$result = $s3client->putObject([
		'Bucket' => 'capital-technology',
		'Key' => 'img2.jpeg',
		'ACL' => 'public-read',
		'SourceFile' => 'aaa.jpeg',
		'ContentType' => mime_content_type('aaa.jpeg'),
]);

echo $result['ObjectURL'];

aws sdk for php v3

まずcomposerをいれます。

$ curl -sS https://getcomposer.org/installer | php

続いて、aws sdkをinstallします。

$ composer require aws/aws-sdk-php
Using version ^3.62 for aws/aws-sdk-php
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 6 installs, 0 updates, 0 removals
  - Installing mtdowling/jmespath.php (2.4.0): Downloading (100%)
  - Installing psr/http-message (1.0.1): Loading from cache
  - Installing guzzlehttp/psr7 (1.4.2): Loading from cache
  - Installing guzzlehttp/promises (v1.3.1): Loading from cache
  - Installing guzzlehttp/guzzle (6.3.3): Downloading (100%)
  - Installing aws/aws-sdk-php (3.62.2): Downloading (100%)
guzzlehttp/guzzle suggests installing psr/log (Required for using the Log middleware)
aws/aws-sdk-php suggests installing doctrine/cache (To use the DoctrineCacheAdapter)
aws/aws-sdk-php suggests installing aws/aws-php-sns-message-validator (To validate incoming SNS notifications)
Writing lock file
Generating autoload files

swift4でARアプリを作ろう

まず、Augmented Reality Appを選択する必要がある。

AppDelegate.swift, ViewController.swift, Main.storyboard, LaunchScreen.storyboard, Info.plist は同じだが、art.scnassetsが追加されている。

viewController.swift
デフォルトでvr体験できるようになってますね。

import UIKit
import SceneKit
import ARKit

class ViewController: UIViewController, ARSCNViewDelegate {

    @IBOutlet var sceneView: ARSCNView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Set the view's delegate
        sceneView.delegate = self
        
        // Show statistics such as fps and timing information
        sceneView.showsStatistics = true
        
        // Create a new scene
        let scene = SCNScene(named: "art.scnassets/ship.scn")!
        
        // Set the scene to the view
        sceneView.scene = scene
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // Create a session configuration
        let configuration = ARWorldTrackingConfiguration()

        // Run the view's session
        sceneView.session.run(configuration)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // Pause the view's session
        sceneView.session.pause()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Release any cached data, images, etc that aren't in use.
    }

    // MARK: - ARSCNViewDelegate
    
/*
    // Override to create and configure nodes for anchors added to the view's session.
    func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
        let node = SCNNode()
     
        return node
    }
*/
    
    func session(_ session: ARSession, didFailWithError error: Error) {
        // Present an error message to the user
        
    }
    
    func sessionWasInterrupted(_ session: ARSession) {
        // Inform the user that the session has been interrupted, for example, by presenting an overlay
        
    }
    
    func sessionInterruptionEnded(_ session: ARSession) {
        // Reset tracking and/or remove existing anchors if consistent tracking is required
        
    }
}