IOS 之爲webView設置UserAgent

今天做webView網頁的時候遇到一個問題就是設置http的頭請求  在網上搜了一段代碼 


在你主要視圖控制器或者程序主類(app delegate)裏面添加以下函數:

+ (void)initialize {

    // Set user agent (the only problem is that we can't modify the User-Agent later in the program)

    NSDictionary *dictionnary = [[NSDictionary alloc]initWithObjectsAndKeys:@"Your desired user agent"@"UserAgent"nil];

    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

    [dictionnary release];

}

但是使用的時候發現 http的頭裏面 就只有設置的這個字段了 ,其他的信息全部沒有了  對後臺去判斷設備什麼的都很不方便 沒有辦法 就有在網上瞎逛了一會但是沒找到很好的解決辦法  最後忽然大迷糊了一下 就明白了綜合了一下網上的知識  寫出了以下代碼  測試了下可以使用  ^_^  看的博客給出來謝謝這些大神們鋪的路  


http://www.mphweb.com/en/blog/easily-set-user-agent-uiwebview


http://blog.csdn.net/mangosnow/article/details/38798195

摸索了兩個小時左右 希望給別人一些幫助 把自己的代碼貼出來

[self setUserAgentForWoapp];


-(void)setUserAgentForWoapp

{

    // Set user agent (the only problem is that we can't modify the User-Agent later in the program)

    UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];

    NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

    NSString *newUagent = [NSString stringWithFormat:@"%@/Your desired user agent",secretAgent];

    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newUagent, @"UserAgent", nil];

    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

    webView = nil;

}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章