import Alamofire

作ってもらった。
alamofirをimportしている。

import UIKit
import Alamofire


class ViewController: UIViewController {
    
    @IBOutlet weak var categoryLbl: UILabel!
    @IBOutlet weak var brandLbl: UILabel!
    @IBOutlet weak var nameLbl: UILabel!
    @IBOutlet weak var priceLbl: UILabel!
    @IBOutlet weak var conditionLbl: UILabel!
    @IBOutlet weak var timeleftLbl: UILabel!
    @IBOutlet weak var bitLbl: UILabel!
    
    @IBOutlet weak var topImg: UIImageView!
    @IBOutlet weak var tittleLbl: UILabel!
    let URL = "http://hpscript.com/xcode/"
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        //making a post request
        Alamofire.request(URL, method: .get, parameters: nil).responseJSON
            {
                response in
                //printing response
                
                
                //getting the json value from the server
                if let result = response.result.value {
                    let jsonData = result as! NSDictionary
                   print(jsonData)
                    self.tittleLbl.text = jsonData.value(forKey: "name") as? String
                    self.bitLbl.text = jsonData.value(forKey: "bit") as? String
                    self.brandLbl.text = jsonData.value(forKey: "brand") as? String
                    self.categoryLbl.text = jsonData.value(forKey: "category") as? String
                    self.conditionLbl.text = jsonData.value(forKey: "condition") as? String
                    self.nameLbl.text = jsonData.value(forKey: "name") as? String
                    self.priceLbl.text = jsonData.value(forKey: "price") as? String
                    self.timeleftLbl.text = jsonData.value(forKey: "timeleft") as? String
                    //if there is no error
                }
        }
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

Alamofire.request(URL, method: .get, parameters: nil).responseJSON か。
alamofireのframe workを入れるところと、getだから、postの場合どうするかだね。

DispatchQueue.main.async

DispatchQueue.main.asyncでjsonを参照する。

override func viewDidLoad() {
        super.viewDidLoad()
        let stringUrl = "http://hpscript.com/swift/index.php"
        do {
            guard let url = URL(string: stringUrl) 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)
                DispatchQueue.main.async {
                    self.label.text = json[0].name //←ここでjsonを参照する
                }
                }.resume()
            
        } catch{
        }
    }

jsonはcodableを使う。
なるほど!行けるか???行ければandroidへ直ぐにGo

swift4 – mysqlを設計していく

どうしてもやりたい

表示したいこと
Category: Audio Player
Brand: AKG
Name:AKG K77 PERCEPT
Price: 40
condition: 30
Left: 300
Bit : 1

まず、mysqlのテーブルを作っていく

create table product(
 category varchar(255),
 brand varchar(255),
 name varchar(255),
 price int,
 condition varchar(255),
 timeleft int,
 bit int,
);

データを入れる。

INSERT INTO `product` (`category`, `brand`, `name`, `price`, `con`, `tleft`, `bit`) VALUES ('Audio Player', 'AKG', 'AKG K77 PERCEPT', '40', 'new', '300', '1');

sessin.dataTaskにいよるget

override func viewDidLoad() {
        super.viewDidLoad()
        let stringUrl = "http://hpscript.com/swift/index.php"
        let url = URL(string: stringUrl)
        let request = URLRequest(url: url!)
        
        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main)
        
        let task:URLSessionDataTask = session.dataTask(with: request, completionHandler: {(data, response, error) in
            if error != nil {
                print(error!)
                return
            }
            
            DispatchQueue.main.async{
                
            }
        })
        task.resume()
        // Do any additional setup after loading the view, typically from a nib.
    }

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!
    
}

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