什么是User Agent?
簡單的說,User Agent就是用來識別瀏覽器名稱、版本、引擎以及操作系統(tǒng)等信息的內(nèi)容。
于是乎,User Agent的判斷就成為識別瀏覽器的關(guān)鍵,不僅僅如此,移動(dòng)互聯(lián)網(wǎng)開發(fā)勢頭迅猛,那么通過User Agent判斷桌面端設(shè)備或移動(dòng)設(shè)備就變的很為重要。當(dāng)然,通過User Agent也可以用來改善一定的兼容性,比如判斷得到用戶用IE6瀏覽器那么就是用不同的代碼。這些,我想許多的WEB開發(fā)中已經(jīng)成為考慮的第一個(gè)問題。
那么,有沒有一種好的判斷User Agent的代碼呢?網(wǎng)上應(yīng)該有很多,比較簡單的直接判斷下iOS和Android,然后進(jìn)入不一樣的頁面
iOS配合
.h文件
#import@interface UIWebView (UserAgent)
- (void)resetUserAgent;
@end
.m文件
#import "UIWebView+UserAgent.h"
@implementation UIWebView (UserAgent)
- (void)resetUserAgent
{
NSString * Agent = [self stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString * newAgent = nil;
newAgent = [Agent stringByAppendingString:@" 名稱_APP"];
NSDictionary * dic = [[NSDictionary alloc]initWithObjectsAndKeys:newAgent,@"UserAgent", nil];
[[NSUserDefaults standardUserDefaults]registerDefaults:dic];
}
@end
使用:
UIWebView * ceshiwebView=[[UIWebView alloc]init];
[ceshiwebView resetUserAgent];