码迷,mamicode.com
首页 > 移动开发 > 详细

ios内嵌浏览器cookie保存

时间:2014-06-29 07:39:02      阅读:996      评论:0      收藏:0      [点我收藏+]

标签:http   java   get   使用   width   文件   

//

//  FMUIWebViewBridge.h

//  sgcard

//

//  Created by Apple on 13-9-10.

//

//

 

#import <Foundation/Foundation.h>

#import <CoreLocation/CoreLocation.h>

#import <UIKit/UIKit.h>

 

#import "FMLayerWebView.h"

 

@interface FMUIWebViewBridge : NSObject<UIWebViewDelegate, UIAlertViewDelegate>

{

    CFMLayerWebView * mLayerWebView;

    UIWindow        * mWindow;

    UIView          * mView;

    UIWebView       * mWebView;

    UIToolbar       * mToolbar;

    UIBarButtonItem * mBackButton;

    NSString        * mUrl;

    NSData          * mData;

}

 

- (void)setLayerWebView : (CFMLayerWebView*) iLayerWebView URLString:(const char*) urlString;

- (void)backClicked:(id)sender;

- (void)webViewDidStartLoad:(UIWebView *)webView;

- (void)webViewDidFinishLoad:(UIWebView *)webView;

- (BOOL)webView:(UIWebView *)webView

        shouldStartLoadWithRequest:(NSURLRequest *)request

        navigationType:(UIWebViewNavigationType)navigationType;

 

- (void) addCookiesToDisk:(NSString *)path withData:(NSMutableDictionary *)cookiesData;

 

- (NSMutableDictionary *) getCookiesFromDisk:(NSString *)path;

 

 

#define COOKIES_PATH "cookies/"

#define COOKIES_FILE "data"

 

@end

 

//

//  FMUIWebViewBridge.cpp

//  sgcard

//

//  Created by Apple on 13-9-10.

//

//

 

#import "FMUIWebViewBridge.h"

#import "EAGLView.h"

 

#include "GameAdapt.h"

 

//用于处理 cookie 相关的头文件

#include <dirent.h>

#include <sys/stat.h>

 

usingnamespacecocos2d;

usingnamespacesgcard;

 

@implementation FMUIWebViewBridge

- (id)init

{

    if(self = [super init])

    {

        mData = nil;

        

        //在网页启动时加存放在磁盘中的 cookies 加载进来

        //debuging - add cookies to uiwebview

        //获得读写位置

        std::string path = CCFileUtils::sharedFileUtils()->getWritablePath();

        path.append(COOKIES_PATH);

        NSString *nspath = [NSStringstringWithCString:path.c_str() encoding:NSUTF8StringEncoding];

        NSMutableDictionary *data = [self getCookiesFromDisk:nspath];

        NSEnumerator *keys = [data keyEnumerator];

        NSHTTPCookieStorage *cookies = [NSHTTPCookieStoragesharedHTTPCookieStorage];

        id key;

        NSHTTPCookie *cookie = nil;

        NSLog(@"read from disk ============= start");

        while ((key = [keys nextObject])) {

            cookie = [data valueForKey:key];

            NSLog(@"read from disk =============%@", cookie);

            [cookies setCookie:cookie];

        }

        NSLog(@"read from disk ============= end");

    }

    returnself;

}

 

- (void)dealloc

{

    //在网页退出时将 cookies 保存在 存储空间中

    //store cookies

    NSHTTPCookie *cookie;

    NSHTTPCookieStorage *cookies = [NSHTTPCookieStoragesharedHTTPCookieStorage];

    NSMutableDictionary *data = [[NSMutableDictionaryalloc] init];

    //获得读写位置

    std::string path = CCFileUtils::sharedFileUtils()->getWritablePath();

    path.append(COOKIES_PATH);

    NSString *nspath = [NSStringstringWithCString:path.c_str() encoding:NSUTF8StringEncoding];

    

    int x= 0;

    for(cookie in [cookies cookies]) {

        NSLog(@"%d =============%@", x++, cookie);

        if(!cookie.isSessionOnly)

            [data setObject:cookie forKey:cookie.name];

    }

    NSLog(@"============= addCookiesToDisk start");

    [selfaddCookiesToDisk:nspath withData:data];

    NSLog(@"============= addCookiesToDisk end");

    NSLog(@"============= self: %@", self);

 

    mLayerWebView->onClose();

    //[mWebView release];

    [mWindowrelease];

    [super dealloc];

}

 

-(void) setLayerWebView : (CFMLayerWebView*) iLayerWebView URLString:(const char*) urlString

{

    mLayerWebView   = iLayerWebView;

    CCSize size     = CGameAdapt::get()->size();

    float coeffi    = CGameAdapt::get()->coefficient();

//    float width     = ( size.width * coeffi ) / [UIScreen mainScreen].scale;

//    float height    = ( size.height * coeffi ) / [UIScreen mainScreen].scale;

    //将网页设置为全屏

    float width     = [UIScreenmainScreen].bounds.size.width;

    float height    = [UIScreenmainScreen].bounds.size.height;

    //Bottom size

    int wBottomMargin = 50 * coeffi / [UIScreen mainScreen].scale;

    mWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, wBottomMargin

                                                           , width, height - wBottomMargin )];

    /*

    mWebView = [[UIWebView alloc] initWithFrame:CGRectMake( CGameAdapt::get()->offsetx() * coeffi / [UIScreen mainScreen].scale

                                                           , CGameAdapt::get()->offsety() * coeffi / [UIScreen  mainScreen].scale + wBottomMargin

                                                           , width, height - wBottomMargin )];

    */

    NSLog(@"============ width: %f, height: %f", width, height);

    

    mWebView.delegate = self;

    [mWebViewsetUserInteractionEnabled:NO]; //don‘t let the user scroll while things are

    // add the webView to the view

    EAGLView * view = [EAGLView sharedEGLView];

    [view.windowmakeKeyAndVisible];

    [view addSubview:mWebView];

    

    mUrl = [NSStringstringWithCString:urlString encoding:NSUTF8StringEncoding];

    id request = [NSURLRequestrequestWithURL:[NSURLURLWithString:mUrl]];

    [mWebViewloadRequest:request];

    //[NSURLConnection connectionWithRequest:request delegate:self];

}

 

//- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data

//{

//    if (mData == nil) {

//        mData = [[NSMutableData alloc] initWithData:data];

//    } else {

//        [mData appendData:data];

//    }

//    NSLog(@"response connection");

//}

//

//- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection

//{

//    NSString *responseString = [[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding];

//    NSLog(@"response body%@", responseString);

//    [mWebView loadHTMLString:responseString baseURL:[NSURL URLWithString:mUrl]];

//    [mWebView setUserInteractionEnabled:YES];

//    

//    mLayerWebView->webViewDidFinishLoad();

//}

 

- (void)webViewDidStartLoad:(UIWebView *)thisWebView

{

    

}

 

- (void)webViewDidFinishLoad:(UIWebView *)thisWebView

{

    //[self.view.window makeKeyAndVisible];

    [mWebViewsetUserInteractionEnabled:YES];

    NSString *swizzleCloseWindowJS =

    @"var script = document.createElement(‘script‘);"

    "script.type = ‘text/javascript‘;"

    "script.text = \"window.close = function windowOnClose() { "

    "   javascript:window.location=‘hackCloseWindowFrame://‘"

    "}\";"

    "document.getElementsByTagName(‘head‘)[0].appendChild(script);";

    [mWebViewstringByEvaluatingJavaScriptFromString:swizzleCloseWindowJS];

    

    mLayerWebView->webViewDidFinishLoad();

}

 

- (void)webView:(UIWebView *)thisWebView didFailLoadWithError:(NSError *)error

{

    if ([error code] != -999 && error != NULL)

    { //error -999 happens when the user clicks on something before it‘s done loading.

        UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:@"Network Error"message:@"Unable to load the page. Please keep network connection."

                                                       delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];

        [alert show]; 

        [alert release]; 

    }

}

 

- (void)backClicked:(id)sender

{

    mWebView.delegate = nil

    [mToolbarremoveFromSuperview]; 

    [mWebViewremoveFromSuperview]; 

    [mViewremoveFromSuperview]; 

    mLayerWebView->onBackbuttonClick(); 

}

 

- (BOOL)webView:(UIWebView *)webView

        shouldStartLoadWithRequest:(NSURLRequest *)request

        navigationType:(UIWebViewNavigationType)navigationType

{

    NSLog( @"absolute url :%@", request.URL.absoluteString );

    NSLog( @"url scheme :%@", request.URL.scheme );

 

    if ([request.URL.schemeisEqualToString:[@"hackCloseWindowFrame"lowercaseString]])

    {

        [self backClicked:nil];

        return NO;

    }

    

    //跳转的字符串格式为 sgapp:openid:{openid}:nick:{nikename}

    NSString *requestString = request.URL.absoluteString;

    NSArray *components = [requestString componentsSeparatedByString:@":"];

    if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"sgapp"])

    {

        const char *idx = NULL;

        const char *name = NULL;

        if([(NSString *)[components objectAtIndex:1] isEqualToString:@"openid"])

        {

//            const char * idx =[(NSString *)[components objectAtIndex:2] UTF8String];

            idx =[(NSString *)[components objectAtIndex:2] UTF8String];

            CCLOG("========== id: %s", idx);

//            mLayerWebView->onQQLogin( idx, NULL );

        }

        

        //兼容老版本只有 idx 值的情况

        if([components count] > 4 && [(NSString *)[components objectAtIndex:3] isEqualToString:@"nick"])

        {

            //由于使用 url, 所以中文字符会被 encode 成另外格式的字符串 (%??)

            //所以需要 decode

//            name = [(NSString *)[components objectAtIndex:4] UTF8String];

            name = [[(NSString *)[components objectAtIndex:4] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] UTF8String];

            CCLOG("========== name: %s", name);

        }

        

        

        //放在 cookie 保存之后, 因为 onQQLogin 执行完成后 FMUIWebViewBridge 对象就被 release 掉了

        mLayerWebView->onQQLogin( idx, name );

        return NO;

    }

    

    returnYES;

}

 

- (void) addCookiesToDisk:(NSString *)path withData:(NSMutableDictionary *)cookiesData {

    

    NSLog(@"========== addCookiesToDisk cookies: path: %@", path);

    DIR *pdir = opendir([path cStringUsingEncoding:NSUTF8StringEncoding]);

    if( !pdir) {

        mkdir([path cStringUsingEncoding:NSUTF8StringEncoding], S_IRWXU | S_IRWXG | S_IRWXO);

    }

    

    NSString *savePath = [path stringByAppendingString:[NSStringstringWithCString:COOKIES_FILEencoding:NSUTF8StringEncoding]];

    [NSKeyedArchiver archiveRootObject:cookiesData toFile:savePath];

    

}

 

- (NSMutableDictionary *) getCookiesFromDisk:(NSString *)path {

    DIR *pdir = opendir([path cStringUsingEncoding:NSUTF8StringEncoding]);

    if(!pdir) {

        NSLog(@"========== getCookiesFromDisk file don‘t exists");

        return nil;

    }

    else {

        NSLog(@"========== getCookiesFromDisk cookies: path: %@", path);

        NSString *savePath = [path stringByAppendingString:[NSStringstringWithCString:COOKIES_FILEencoding:NSUTF8StringEncoding]];

        return [NSKeyedUnarchiverunarchiveObjectWithFile:savePath];

    }

}

 

@end

ios内嵌浏览器cookie保存,布布扣,bubuko.com

ios内嵌浏览器cookie保存

标签:http   java   get   使用   width   文件   

原文地址:http://www.cnblogs.com/sealme/p/3770119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!