Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした