Sunday, October 11, 2015

Open the browser with a URL including Unicode characters 以瀏覽器開啟中文網址

The following example is written with Xcode 6.4. It converts a string with Unicode characters to the NSURL format.

Edit ViewController.swift as below:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button = UIButton(frame: CGRectMake(100, 100, 100, 20))
        button.setTitle("Press", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)//Set the title color while highlighted
        button.addTarget(self, action: "btnPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(button)
    }
    
    func btnPressed(sender: UIButton) {
        println("btnPressed")
        
        let string = "https://tw.news.yahoo.com/ios-9-0-1釋出-網友:滑臉書好快喔-083210396.html".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
        
        let url = NSURL(string: string!)
        UIApplication.sharedApplication().openURL(url!)//Open the URL in the browser.
    }

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

}

After pressing the 'Press' button, the browser is opened with the  URL in Chinese.


1 comment: