does NSURLSession send user-agent automatically

2019-04-01 02:50发布

问题:

Does NSURLSession send user-agent automatically when user WatchKit 2.0, iOS 9.0? Is there a way to verify this within the WatchKit app?

回答1:

Yes, a user agent is automatically provided as part of the default session configuration.

The default NSURLSession request header User-Agent field includes the Bundle Name (CFBundleName) and the Build Number (CFBundleVersion) of your watchOS app extension:

$(CFBundleName)/$(CFBundleVersion) CFNetwork/808.3 Darwin/16.3.0

Notice that your app's Version Number (CFBundleShortVersionString) isn't included. (See Technical Note TN2420: Version Numbers and Build Numbers for more info.)

For example, for product "Foo" with the Build Number 1, your user agent would be:

Foo%20WatchKit%20Extension/1 CFNetwork/808.3 Darwin/16.3.0

How to Verify?

I don't think there's a way within your app to examine the default user agent field, as it's nil (unless you've set it to a custom value).

But, you could use netcat to examine requests sent by the Simulator.

  1. Run nc -l 5678 in Terminal to have netcat listen to requests sent to localhost on port 5678

  2. In your app's Info.plist file, add the App Transport Security Settings dictionary with the Allow Arbitrary Loads key set to YES

  3. Add the following code to the start of application(_:didFinishLaunchingWithOptions:)

    let url = URL(string: "http://localhost:5678/")!
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        let body = String(data: data!, encoding: .utf8)!
        print("body: \(body)")
    }.resume()
    return true
    
  4. Run your app in the Simulator and see what netcat outputs in Terminal

If your privacy is of no concern, you could use a service like user-agent.me to test on your device.

  1. Replace localhost:5678 above with user-agent.me

  2. Run your app on your device

  3. Examine Xcode's Console output

When you're done verifying, remember to undo all of the changes above.



回答2:

Related to your question, note that it is possible to manually set the User-Agent string for your NSURLSession in WatchKit, using a NSURLSessionConfiguration object and setting HTTPAdditionalHeaders.