レベルエンター山本大のブログ

面白いプログラミング教育を若い人たちに

Swiftのちょっとしたメモ

PlayGroundでHTTP通信

import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let session = URLSession(configuration: .default)

var urlComponents = URLComponents(string: "http://localhost/json")!

urlComponents.query = "method=get"

let url = urlComponents.url!

let request = URLRequest(url: url)

let task = session.dataTask(with: request) { (data, response, error) in
    guard let data = data else { print("HTTP通信でエラー"); return  }

    let json = String(data: data, encoding: .utf8)!
    print(json)
}
task.resume()
session.finishTasksAndInvalidate()

オートレイアウトをコードで実装する

import UIKit

class ViewController: UIViewController {

    var sampleView: UIView!
    
    override func loadView() {
        super.loadView()
        sampleView = UIView(frame: .zero)
        sampleView.backgroundColor = UIColor.red
        sampleView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(sampleView)
        
        let sa = self.view.safeAreaLayoutGuide;
        sampleView.centerXAnchor.constraint(equalTo: sa.centerXAnchor).isActive = true
        sampleView.centerYAnchor.constraint(equalTo: sa.centerYAnchor).isActive = true
        sampleView.topAnchor.constraint(equalTo: sa.topAnchor,constant: 10.0).isActive = true
        sampleView.bottomAnchor.constraint(equalTo: sa.bottomAnchor,constant: -10.0).isActive = true
        sampleView.leadingAnchor.constraint(equalTo: sa.leadingAnchor,constant: 10.0).isActive = true
        sampleView.trailingAnchor.constraint(equalTo: sa.trailingAnchor,constant: -10.0).isActive = true
    }

    override func viewDidLoad() {
        super.viewDidLoad()       
    }
}

URLカスタムスキームでのアプリ連携

プロジェクトの設定、 info -> URLTypes -> URL Schemes  「myapp」(://とかはいらない)

呼び出しボタンのアクション接続などで

let url = URL(string: "myapp://")!
let app = UIApplication.shared
app.open(url , options: [:] ,completionHandler: nil )