11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftでUserAgentを偽装し、iPhoneからPCのWebサイトを見る

Posted at

SwiftでUserAgentを書き換える

iOSのWebView使って、PC版サイトを表示したいとき。

func changeUserAgent(){
    let userAgentStr = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.63 Safari/537.36"
    let dic:NSDictionary = ["UserAgent":userAgentStr]
    NSUserDefaults.standardUserDefaults().registerDefaults(dic)
}

実装ソース

import UIKit

class FirstViewController: UIViewController,UIWebViewDelegate {
    @IBOutlet weak var twitterWebView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        changeUserAgent()
        loadTwitterWebView()
    }

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

    // UA書き換え
    func changeUserAgent(){
        let userAgentStr = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.63 Safari/537.36"
        let dic:NSDictionary = ["UserAgent":userAgentStr]
        NSUserDefaults.standardUserDefaults().registerDefaults(dic)
    }

    // webview load
    func loadTwitterWebView(){
        twitterWebView.delegate = self
        let url: NSURL = NSURL(string: "http://twitter.com")!
        let request: NSURLRequest = NSURLRequest(URL: url)
        twitterWebView.loadRequest(request)
    }

    /*
    Pageがすべて読み込み終わった時呼ばれる
    */
    func webViewDidFinishLoad(webView: UIWebView!) {
        println("webViewDidFinishLoad")
        println(webView.request?.URL)
    }

    /*
    Pageがloadされ始めた時、呼ばれる
    */
    func webViewDidStartLoad(webView: UIWebView!) {
        println("webViewDidStartLoad")
        println(webView.request?.URL)
    }
}

結果

iOS Simulator Screen Shot 2015.03.14 16.29.37.png

11
9
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
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?