3
1

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 1 year has passed since last update.

Xcode15でビルドするとUserDefaultsからのUserAgentの変更ができなくなる(iOS17のみ)

Posted at

Xcode15でビルドするとUserDefaultsからのUserAgentの変更が効いてないことがあったので調べてみました。

調査内容

こちらのコードをXcode15でビルドし、各OSでの出力(UserAgent)を確認します。

サンプルコード

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UserDefaults.standard.register(defaults: ["UserAgent": "test user agent"])
        return true
    }
}
import UIKit
import WebKit

class ViewController: UIViewController {
    let webview = WKWebView()

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        webview.evaluateJavaScript("navigator.userAgent;") { result, _ in
            print("UserAgent: \(result ?? "nil")")
        }
    }
}

結果

iOS17だとUserAgentが変わっていません!

iOS 15.0 iOS 16.4 iOS 17.0
UserAgent: test user agent UserAgent: test user agent UserAgent: Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148

ちなみにXcode14.3.1でビルドしたものをiOS17で動かした場合は、test user agent になっていました。

対策

WKWebViewのcustomUserAgentを使えばOK

webview.customUserAgent = "test user agent"

まとめ

UIWebView時代の名残りでUserDefaultsのUserAgentを使ってる方はXcode15に移行する際にご注意ください

3
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?