您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“iOS UIWebView如何通過cookie完成自動登錄”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“iOS UIWebView如何通過cookie完成自動登錄”這篇文章吧。
1、相關介紹
iOS在UIWebView中獲取的cookie的方法:NSHTTPCookieStorage * nCookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
再具體獲取某個域的cookie:NSArray* cookiesURL = [nCookies cookiesForURL:[NSURL URLWithString:@"你的URL"]];
通過[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:userCookie]方法將 cookies來保存起來,但是這樣雖然可以保存cookies但是你應用退出之后還是會丟失(其實是cookies過期的問題),做好的方法是把cookies放到NSUserDefaults保存起來.
2、實現
1.在UIWebView的代理方法中實現獲取cookies并將cookies放到NSUserDefaults保存起來:- (void)webViewDidFinishLoad:(UIWebView*)webView中寫入
- (void)webViewDidFinishLoad:(UIWebView*)webView{ NSArray *nCookies = [[NSHTTPCookieStoragesharedHTTPCookieStorage] cookies]; for (NSHTTPCookie *cookie in nCookies){ if ([cookie isKindOfClass:[NSHTTPCookie class]]){ if ([cookie.name isEqualToString:@"PHPSESSID"]) { NSNumber *sessionOnly =[NSNumber numberWithBool:cookie.sessionOnly]; NSNumber *isSecure = [NSNumber numberWithBool:cookie.isSecure]; NSArray *cookies = [NSArray arrayWithObjects:cookie.name, cookie.value, sessionOnly, cookie.domain, cookie.path, isSecure, nil]; [[NSUserDefaults standardUserDefaults] setObject:cookies forKey:@"cookies"]; break; } } } }
2.獲取cookies:運行之后,UIWebView加載url之前獲取保存好的cookies,并設置cookies,
NSArray *cookies =[[NSUserDefaults standardUserDefaults] objectForKey:@"cookies"]; if (cookies.count >0) { NSMutableDictionary *cookieProperties = [NSMutableDictionarydictionary]; [cookieProperties setObject:[cookies objectAtIndex:0] forKey:NSHTTPCookieName]; [cookieProperties setObject:[cookies objectAtIndex:1] forKey:NSHTTPCookieValue]; [cookieProperties setObject:[cookies objectAtIndex:3] forKey:NSHTTPCookieDomain]; [cookieProperties setObject:[cookies objectAtIndex:4] forKey:NSHTTPCookiePath]; NSHTTPCookie *cookieuser = [NSHTTPCookiecookieWithProperties:cookieProperties]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser]; }
注意:要在[self.webView loadRequest:req];之前設置獲取cookies!
以上是“iOS UIWebView如何通過cookie完成自動登錄”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。