iOS and H5 interaction, H5 need to use useragent with some parameters, we need to modify the default useragent for the custom.
First of all, to popularize the history of useragent, click useragent View.
Search the Internet a lot of information. No one way is good, summed up, the following 2 methods are not useful:
1, directly set the useragent inside the request header
Nsmutableurlrequest *request = [[Nsmutableurlrequest alloc] initwithurl:url];[ Request AddValue:@ "jiecao/2.4.7" Forhttpheaderfield:@ "user-agent "]; [Self.webview loadrequest:request];
2, inside the Appdelegate register a new useragent
//get the original user-agent of WebViewUIWebView *webview =[[UIWebView alloc] Initwithframe:cgrectzero]; NSString*oldagent = [WebView stringbyevaluatingjavascriptfromstring:@"navigator.useragent"]; NSLog (@"Old agent:%@", oldagent); //add my info to the new agentNSString *newagent = [oldagent stringbyappendingstring:@"jiecao/2.4.7 Ch_appstore"]; NSLog (@"new agent:%@", newagent); //regist the new agentNsdictionary *dictionnary = [[Nsdictionary alloc] initwithobjectsandkeys:newagent,@"useragent", nil]; [[Nsuserdefaults Standarduserdefaults] registerdefaults:dictionnary];
Answer: The first method, UserAgent is a read-only property, so failed. The second method, which modifies the global useragent setting, [Nsuserdefault Stangaruserdefault] is a singleton that is overwritten by the default value until the next call is modified. (I guess)
So, the correct way to modify this is to modify the global useragent value before loadrequest.
NSString *customuseragent = [NSString stringWithFormat:@ " %@/%@/%@", @ "WT", @ "IPhone", @ "1.0.0"]; [[Nsuserdefaults standarduserdefaults] registerdefaults:@{@ "useragent": Customuseragent}]; *url = [Nsurl URLWithString:self.requestUrl]; *request = [nsurlrequest requestwithurl:url cachepolicy:nsurlrequestuseprotocolcachepolicy timeOutInterval:F]; [Self.webholder loadrequest:request];
Finally, it is easyjs to do the interaction.
IOS modifies UIWebView's useragent