ios – 是否接受UIWebView中的Cookie?

前端之家收集整理的这篇文章主要介绍了ios – 是否接受UIWebView中的Cookie?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我必须质疑你.

1:我在iPhone App中使用UIWebViews.我不知道用户可以在新闻中添加评论.但是,要评论他们必须登录.

如果没有,我如何在UIWebViews中接受cookies?

2:UIWebView中创建的Cookie是否可以在其他视图中的其他UIWebView中使用?

例如:我有我的LoginViewController,嵌入式UIWebView,我的用户可以登录/注销.如果他们在此视图中登录,该Cookie将仍然可以在CommentViewController中使用?

如果没有,我该如何做到这一点?

提前致谢 !

解决方法

UIWebView将自动将Cookie存储在[NSHTTPCookieStorage sharedHTTPCookieStorage]集合中,并且应该在应用程序启动期间在应用程序的所有其他UIWebView中可用.但是,UIWebView类不会自动存储应用程序启动之间加载的页面的Cookie.当应用程序移动到后台时,您需要手动存储Cookie,并在应用程序返回到前台时重新加载值.

将以下代码放在AppDelegate类中:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Other existing code

    [self loadHTTPCookies];
    return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    //Other existing code

    [self saveHTTPCookies];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [self loadHTTPCookies];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    //Other existing code
    [self saveHTTPCookies];
}

-(void)loadHTTPCookies
{
    NSMutableArray* cookieDictionary = [[NSUserDefaults standardUserDefaults] valueForKey:@"cookieArray"];

    for (int i=0; i < cookieDictionary.count; i++)
    {
        NSMutableDictionary* cookieDictionary1 = [[NSUserDefaults standardUserDefaults] valueForKey:[cookieDictionary objectAtIndex:i]];
        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieDictionary1];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
}

-(void)saveHTTPCookies
{
    NSMutableArray *cookieArray = [[NSMutableArray alloc] init];
    for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
        [cookieArray addObject:cookie.name];
        NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
        [cookieProperties setObject:cookie.name forKey:NSHTTPCookieName];
        [cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue];
        [cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain];
        [cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath];
        [cookieProperties setObject:[NSNumber numberWithUnsignedInteger:cookie.version] forKey:NSHTTPCookieVersion];
        [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

        [[NSUserDefaults standardUserDefaults] setValue:cookieProperties forKey:cookie.name];
        [[NSUserDefaults standardUserDefaults] synchronize];

    }

    [[NSUserDefaults standardUserDefaults] setValue:cookieArray forKey:@"cookieArray"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
原文链接:/iOS/336864.html

猜你在找的iOS相关文章