LoginSignup
1
1

More than 5 years have passed since last update.

[Swift] NSURLを生成してSafari起動

Last updated at Posted at 2015-09-02

ソースはこれまでのものを流用します。

SwiftでのTableView modal画面の非表示
http://qiita.com/senseiswift/items/90be98960b4c9dffe6aa

やること

  1. ViewControllerのテーブルに表示するテキストを変更
  2. SwcondViewControllerのテーブルの行数を追加
  3. テーブルの2行目に文言を追加
  4. テーブルの2行目をタップした時にURLを生成してSafariを起動

NSURLの生成とブラウザ起動部分

NSURL
    var url : NSString = "(参照したいURL)"
    var urlStr : NSString = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
    var searchURL : NSURL = NSURL(string: urlStr as String)!

    // ブラウザ起動
    if UIApplication.sharedApplication().canOpenURL(searchURL){
        UIApplication.sharedApplication().openURL(searchURL)
    }

ソース全文

ViewController
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    // SecondViewに渡す文字列
    var selectedText: String?

    // 選択状態を解除するIndexPathを入れる変数
    var selectedRow: NSIndexPath?

    // 1. テーブルに表示するテキストを変更
    let texts = ["マクドナルド", "モスバーガー", "バーガーキング", "ウェンディーズ", "フレッシュネスバーガー", "サブウェイ"]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }

    // 4画面が表示される時に呼ばれるメソッドを追加
    override func viewWillAppear(animated: Bool) {
        super.viewDidDisappear(animated)

        // selectedRowがセットされていたら選択を解除する
        if (selectedRow != nil)
        {
            tableView?.deselectRowAtIndexPath(selectedRow!, animated: false)
        }
    }

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

    // セルの行数
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return texts.count
    }

    // セルのテキストを追加
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")

        cell.textLabel?.text = texts[indexPath.row]
        return cell
    }

    func tableView(table: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {
        println(texts[indexPath.row])

        // SecondViewControllerに渡す文字列をセット
        selectedText = texts[indexPath.row]

        // SecondViewControllerへ遷移するSegueを呼び出す
        performSegueWithIdentifier("showSecondView",sender: nil)

        // 選択状態を解除するIndexPathをセット
        selectedRow = indexPath
    }

    // Segueで遷移時の処理
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if (segue.identifier == "showSecondView") {
            let secondVC: SecondViewController = (segue.destinationViewController as? SecondViewController)!

            // SecondViewControllerのtextに選択した文字列を設定する
            secondVC.text = selectedText
        }
    }
}
SecondViewController
import UIKit

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    // ViewControllerから受け取る文字列を入れる変数
    var text: String?

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }

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

    // 2. テーブルの行数を追加
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    // セルのテキストを追加
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")

        if (indexPath.row == 0)
        {
            // 受け取った文字列をセルに表示
            cell.textLabel?.text = text
            return cell
        }
        else if (indexPath.row == 1)
        {
            // 3. テーブルの2行目に文言を追加
            cell.textLabel?.text = text! + "についてGoogleで調べる"
            return cell
        }

        return cell
    }

    func tableView(table: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {

        if (indexPath.row == 0)
        {
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        else if (indexPath.row == 1)
        {
            // 4. テーブルの2行目をタップした時にURLを生成してSafariを起動
            var url : NSString = "https://www.google.co.jp/search?q=" + text!
            var urlStr : NSString = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
            var searchURL : NSURL = NSURL(string: urlStr as String)!
            println(searchURL)

            if UIApplication.sharedApplication().canOpenURL(searchURL){
                UIApplication.sharedApplication().openURL(searchURL)
            }
        }
    }
}

参考ソース
https://github.com/senseiswift/tableviewtest/commit/03e047e1651123a5c05195f33ff69101f9908b29

次回はTwitter投稿をできるようにしました。
[Swift] SLComposeViewControllerdでTwitter投稿
http://qiita.com/senseiswift/items/9832146fa3d563640156

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1