问题
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.
Run
nc -l 5678in Terminal to have netcat listen to requests sent tolocalhoston port5678In your app's
Info.plistfile, add the App Transport Security Settings dictionary with the Allow Arbitrary Loads key set toYESAdd 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 trueRun 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.
Replace
localhost:5678above withuser-agent.meRun your app on your device
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.
来源:https://stackoverflow.com/questions/36379347/does-nsurlsession-send-user-agent-automatically