PIYO - Tech & Life -

UIWebView内リンクでの遷移をNavigationでやるやつ、Swiftバージョン

Hybrid iOS Swift Web

iOSでUIWebView内のリンクをタップしたらNavigationで画面遷移させる実験 - ぴよログ

↑こんなん書いたけどこのときはObjective-Cで書いてたのでSwiftで書き換えてみました。オプショナルが全然慣れませんがこれから勉強します。

import UIKit
import TKRSegueOptions

class ViewController: UIViewController, UIWebViewDelegate {

    let HOST = "http://localhost:4000"

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        webView.delegate = self
        var urlstring = HOST + "/"
        if let path = self.segueOptions?["path"] as? String {
            urlstring = HOST + path
        }
        let url = NSURL(string: urlstring)
        let req = NSURLRequest(URL: url!)
        webView.loadRequest(req)
    }

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

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        if(request.URL?.scheme == "callback"){
            println(request.URL?.absoluteString)
            let urlstring = request.URL?.absoluteString
            let href = urlstring?.substringFromIndex(advance(urlstring!.startIndex, 11))
            performSegueWithIdentifier("next", options: ["path": href!])
        }
        return true
    }
}