iOS开发总结-UIWebView 集成 浏览器

 

//
//  detailWebViewController.m
//  BJ
//
//  Created by shirenfeng on 16/11/6.
//  Copyright © 2016年 com.wsb123. All rights reserved.
//  浏览器
#import "detailWebViewController.h"
#import "DBStrore.h"
#import "BaseSVRRequestOperator.h"
#import "Utilities.h"
#import "FTMacro.h"
#import "AppDelegate.h"
#import "HttpConnect.h"
#import<CommonCrypto/CommonDigest.h>
@interface detailWebViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIButton *capPicBtn;
@property (nonatomic, strong) UIButton *shopName;
@property (nonatomic, strong) UIButton *mReloadBtn;
@property (nonatomic, strong) UIWebView *mWebView;
@property (nonatomic, strong) BaseSVRRequestOperator *netWorking;
@property (nonatomic, strong) NSMutableArray *clientArray;
@property (nonatomic,strong) NSString *loadedURL;
#define MAXCOUNT 30
#define MAXTIMEOUT 10
@end

@implementation detailWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //_shopName.frame = CGRectMake((kScreenWidth-100)/2,11,100,30);
    // _capPicBtn.frame = CGRectMake(kScreenWidth-80,11,80,30);
    
    // Do any additional setup after loading the view from its nib.
//    self.navigationController.navigationBarHidden = NO;
    
    
    
    
    [self initview];

}
-(void)initview
{
    for(UIView *view in [self.view subviews])
    {
        [view removeFromSuperview];
    }
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *shopname = [defaults stringForKey:@"shopnamedata"];

    UIButton *returnTextBtn = [[UIButton alloc] initWithFrame:CGRectMake(20,11,80,30)];
    [returnTextBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [returnTextBtn setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
    [returnTextBtn setTitle:[NSString stringWithFormat:@"返回“选123”"] forState: UIControlStateNormal];
    returnTextBtn.backgroundColor = [UIColor clearColor];
    [returnTextBtn setTitleColor:self.view.tintColor forState:UIControlStateNormal];
    returnTextBtn.titleLabel.font = [UIFont systemFontOfSize: 15.0];
    [returnTextBtn addTarget:self action:@selector(returnApp) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:returnTextBtn];
    
    
    
    _shopName = [[UIButton alloc] initWithFrame:CGRectMake((kScreenWidth-130)/2,11,130,30)];
    [_shopName setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [_shopName setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
    _shopName.backgroundColor = [UIColor clearColor];
    [_shopName setTitleColor:[UIColor redColor]forState:UIControlStateNormal];
    _shopName.titleLabel.font = [UIFont systemFontOfSize: 15.0];
    [self.view addSubview:_shopName];
    
    _capPicBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-70,11,70,30)];
    [_capPicBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [_capPicBtn setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
    [_capPicBtn setTitle:[NSString stringWithFormat:@"加入对比"] forState: UIControlStateNormal];
    _capPicBtn.backgroundColor = [UIColor clearColor];
    [_capPicBtn setTitleColor:self.view.tintColor forState:UIControlStateNormal];
    _capPicBtn.titleLabel.font = [UIFont systemFontOfSize: 15.0];
    [_capPicBtn addTarget:self action:@selector(capPicBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_capPicBtn];
    
    
    _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 49, kScreenWidth, 0.9)];
    _lineView.backgroundColor = [UIColor colorWithHue:0 saturation:0 brightness:0.85 alpha:0.85];
    [self.view addSubview:_lineView];
    
    
    _mWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0,50,kScreenWidth,kScreenHeight-50)];
    [self.view addSubview:_mWebView];
    
    
     UIButton *returnimgbtn = [[UIButton alloc] initWithFrame:CGRectMake(2,11,30,30)];
     [returnimgbtn setImage:[UIImage imageNamed:@"back_b.png"]forState:UIControlStateNormal];
     [returnimgbtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
     [returnimgbtn setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
     returnimgbtn.backgroundColor = [UIColor clearColor];
     [returnimgbtn setTitleColor:[UIColor redColor]forState:UIControlStateNormal];
     returnimgbtn.titleLabel.font = [UIFont systemFontOfSize: 15.0];
     [returnimgbtn addTarget:self action:@selector(returnApp) forControlEvents:UIControlEventTouchUpInside];
     [self.view addSubview:returnimgbtn];
    
    
    if([shopname rangeOfString:@"贝贝"].location != NSNotFound || [shopname rangeOfString:@"亚马逊"].location != NSNotFound  || [shopname rangeOfString:@"天猫"].location != NSNotFound){
        UIButton *backimgbtn = [[UIButton alloc] initWithFrame:CGRectMake(10,150,40,40)];
        [backimgbtn setImage:[UIImage imageNamed:@"hb_back.png"]forState:UIControlStateNormal];
        [backimgbtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [backimgbtn setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
        backimgbtn.backgroundColor = [UIColor clearColor];
        [backimgbtn setTitleColor:[UIColor redColor]forState:UIControlStateNormal];
        backimgbtn.titleLabel.font = [UIFont systemFontOfSize: 15.0];
        [backimgbtn addTarget:self action:@selector(backPageBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:backimgbtn];
    }

    // back_b.png   hb_back.png
    
    //    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //    NSString *urlStr = [defaults stringForKey:@"urlshopname"];
    //    if(urlStr){
    //        self.title =urlStr;
    //    }
    
    //    self.mWebView.scalesPageToFit = YES;
    self.mWebView.scrollView.showsVerticalScrollIndicator = YES;
    self.mWebView.hidden = YES;
    self.mWebView.delegate = self;
    self.loadedURL = NULL;
    
    self.netWorking = [BaseSVRRequestOperator new];
    [Utilities addMyGifImageView:self];
    [self addWebViewURL];
    
    [self writeClickRecord];
    
    
    [self performSelector:@selector(timeOut:) withObject:self afterDelay:MAXTIMEOUT];
}
-(void)writeClickRecord
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSNumber *goodsid = [NSNumber numberWithInt:[[defaults stringForKey:@"goodsiddata"] intValue]];
    NSNumber *itemid = [NSNumber numberWithInt:[[defaults stringForKey:@"itemiddata"] intValue]];
    AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
    NSNumber *uuid = [NSNumber numberWithInt:myDelegate.uuid];
    
    HttpConnect * connect = [[HttpConnect alloc] init];
    connect.delegate = self;
    
    NSString *UDID=[DBStrore sharedDBStore].sessionId;
    NSLog(@"write click :%@-%d-%d-%d",UDID,[uuid intValue],[goodsid intValue],myDelegate.share);
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    
    [dic setObject:UDID forKey:@"udid"];
    [dic setObject:uuid forKey:@"uuid"];
    
        
    if([[defaults stringForKey:@"itemiddata"] intValue]==-1){
        NSLog(@"itemid=%d",[itemid intValue]);
        
    }
    else if([[defaults stringForKey:@"itemiddata"] intValue]!=0){
        NSLog(@"itemid=%d",[itemid intValue]);
        [dic setObject:itemid forKey:@"itemid"];
        [connect postRequestForPostValue:dic url:@"addclick.php" requestTag:1];
    }
    else{
        NSNumber *adid = [NSNumber numberWithInt:[[defaults stringForKey:@"adiddata"] intValue]];
        NSLog(@"adid=%d",[adid intValue]);
        [dic setObject:adid forKey:@"adid"];
        [connect postRequestForPostValue:dic url:@"addadclick.php" requestTag:1];
    }

    
    
}

-(void)postRequestStarted:(AFHTTPRequestOperation*)request manage:(AFHTTPRequestOperationManager*)manage{
    
    
    NSLog(@"REQ START");
}
-(void)postRequestFinished:(AFHTTPRequestOperation*)request manage:(AFHTTPRequestOperationManager*)manage{
    
    NSLog(@"REQ FINISHED");
    
    NSDictionary * dictionary = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableLeaves error:nil ];
    NSString * status = [NSString stringWithFormat:@"%@",[dictionary objectForKey:@"status"]];
    
    if([status isEqualToString: @"0"]){
        
        NSLog(@"REQ success");
    }
    else{
        NSLog(@"REQ error status=@%@",status);
    }
    
}
-(void)postRequestFailed:(AFHTTPRequestOperation*)request manage:(AFHTTPRequestOperationManager*)manage{
    
    
    NSLog(@"REQ FAILED");
    
}


- (void)timeOut:(id)time
{
    [Utilities removeMyGifImageView:self.view];
    
    if(self.loadedURL == NULL){
        UIButton *reloadBtn = [[UIButton alloc] initWithFrame:CGRectMake(40/2,100/2,kScreenWidth-40,kScreenHeight-100)];
        [reloadBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
        [reloadBtn setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
        [reloadBtn setTitle:[NSString stringWithFormat:@"重试"] forState: UIControlStateNormal];
        reloadBtn.backgroundColor = [UIColor clearColor];
        [reloadBtn setTitleColor:self.view.tintColor forState:UIControlStateNormal];
        reloadBtn.titleLabel.font = [UIFont systemFontOfSize: 18.0];
        [reloadBtn addTarget:self action:@selector(initview) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:reloadBtn];
        _mReloadBtn=reloadBtn;

    }
}
- (void)backPageBtn
{
    NSLog(@"backPageBtn");
    if([self.mWebView canGoBack])
    {
        [self.mWebView goBack];
    }
    else
    {
        [[DBStrore sharedDBStore] removeInformationView:6];
    }
}
- (void)addWebViewURL
{
//    NSString *urlStr = @"http://www.jd.com";
    //    NSURL *URL = [NSURL URLWithString:str];  //string>url
    //    NSString *str1 = [URL absoluteString];   //url>string
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *urlStr = [defaults stringForKey:@"urldata"];
    NSString *shopname = [defaults stringForKey:@"shopnamedata"];

    [_shopName setTitle:shopname forState: UIControlStateNormal];
    
    NSLog(@"webpage old url:%@",urlStr);
    
    //urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF32StringEncoding];
    NSLog(@"webpage url:%@",urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSURLRequest *request =  [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:MAXTIMEOUT];
    [self.mWebView loadRequest:request];
    NSLog(@"webpage request ok ");
}
- (void)returnApp
{
    NSLog(@"returnApp");
    [[DBStrore sharedDBStore] removeInformationView:6];
}


- (void)capPicBtnClick
{
    NSLog(@"capPic");
    if(self.loadedURL != NULL){
        
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(kCapPicWidth, kCapPicHeight), YES, 1);     //设置截屏大小
        [[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        CGImageRef imageRef = viewImage.CGImage;
        CGRect rect = CGRectMake(kCapPicStartx, kCapPicStarty, kCapPicWidth, kCapPicHeight);//这里可以设置想要截图的区域
        CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
        UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];
        // UIImageWriteToSavedPhotosAlbum(sendImage, nil, nil, nil);//保存图片到照片库
        NSData *imageViewData = UIImagePNGRepresentation(sendImage);
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *pictureName= [NSString stringWithFormat:@"screenShow_%@.png",[self md5:self.loadedURL]];
        NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:pictureName];
        
        NSLog(@"url: %@", self.loadedURL);
        NSString *titlename=[_shopName.titleLabel.text stringByReplacingOccurrencesOfString:@"" withString:@""];
        titlename=[titlename stringByReplacingOccurrencesOfString:@"同品类" withString:@""];
        NSString *key= [NSString stringWithFormat:@"%@,%@,%@",titlename,savedImagePath,self.loadedURL];
        
        NSLog(@"capPicBtnClick count: %d",[DBStrore sharedDBStore].CapPicArray.count);
        
        NSFileManager *fileManager=[[NSFileManager alloc] init];
        NSError *error;
        
        for(int i=0;i<[DBStrore sharedDBStore].CapPicArray.count;i++){
            if([[DBStrore sharedDBStore].CapPicArray[i] isEqualToString:key]){
                NSLog(@"remove  at %d",i);
                
                if([fileManager fileExistsAtPath:savedImagePath]){
                    NSLog(@"del imgpath:%@",savedImagePath);
                    [fileManager removeItemAtPath:savedImagePath error: &error];
                    if(error){
                        NSLog(@"del file error = %@",error);
                    }
                }
                [imageViewData writeToFile:savedImagePath atomically:YES];//保存照片到沙盒目录
                CGImageRelease(imageRefRect);
                [self archivedCapPic];
                
                NSLog(@"notify freshCapPicCount");
                [[NSNotificationCenter defaultCenter] postNotificationName:@"freshCapPicCount" object:nil userInfo:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"capPicChanged" object:nil userInfo:nil];
                [Utilities showAlertView:@"加入成功"];
                return ;
            }
        }

        
        [imageViewData writeToFile:savedImagePath atomically:YES];//保存照片到沙盒目录
        CGImageRelease(imageRefRect);
        
        
        if([DBStrore sharedDBStore].CapPicArray.count == MAXCOUNT)
        {
            NSFileManager *fileManager=[[NSFileManager alloc] init];
            NSError *error;
            
            NSString *keytmp = [DBStrore sharedDBStore].CapPicArray[0];
            NSArray *tmparr=[keytmp componentsSeparatedByString:@","];
            NSString *imagePath=tmparr[1];
            if([fileManager fileExistsAtPath:imagePath]){
                NSLog(@"del imgpath:%@",imagePath);
                [fileManager removeItemAtPath:imagePath error: &error];
                if(error){
                    NSLog(@"del file error = %@",error);
                }
            }
            
            [[DBStrore sharedDBStore].CapPicArray removeObjectAtIndex:0];
            
        }
        NSLog(@"3 saveKey count: %d",[DBStrore sharedDBStore].CapPicArray.count);
        [[DBStrore sharedDBStore].CapPicArray addObject:key];
        NSLog(@"4 saveKey count: %d",[DBStrore sharedDBStore].CapPicArray.count);
        [self archivedCapPic];
        
        NSLog(@"notify freshCapPicCount");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"freshCapPicCount" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"capPicChanged" object:nil userInfo:nil];
        
        [Utilities showAlertView:@"加入成功"];
    }
    else{
        [Utilities showAlertView:@"加载中。。请稍后再试"];
    }
}
- (NSString *) md5:(NSString *) input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}
- (void)archivedCapPic
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *bindUserLocalSettingDictionaryData = [NSKeyedArchiver archivedDataWithRootObject:[DBStrore sharedDBStore].CapPicArray];
    [defaults setObject:bindUserLocalSettingDictionaryData forKey:FTcapPic];
    [defaults synchronize];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark UIWebViewDelegate


- (void )webViewDidFinishLoad:(UIWebView  *)webView
{
//    [self.mWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"common.checkIos('%@')", @"ios"]];
    self.mWebView.hidden = NO;
    [Utilities removeMyGifImageView:self.view];
    self.loadedURL=[NSString stringWithFormat:@"%@",webView.request.URL.absoluteString];
    NSLog(@"webViewDidFinishLoad url:%@",webView.request.URL.absoluteString);
    if(_mReloadBtn!=nil){
        [_mReloadBtn removeFromSuperview];
        _mReloadBtn=nil;
    }
    
    
}

- (void)webView:(UIWebView *)webView  didFailLoadWithError:(NSError *)error
{
    [Utilities removeMyGifImageView:self.view];
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    if(request != nil){
        NSURL *url = request.URL;
        
        if(url !=nil){
            // 要处理的代码
            // ......
            
            NSLog(@"url.scheme=%@",url.scheme);
            //拦截app跳转
            if ([url.scheme isEqualToString:@"weixin"])
            {
                NSLog(@"return weixin");
                return YES;
            }
            if ([url.scheme isEqualToString:@"alipay"])
            {
                NSLog(@"return alipay");
                return YES;
            }
            if (!([url.scheme isEqualToString:@"http"]) && !([url.scheme isEqualToString:@"https"]))
            {
                NSLog(@"return no");
                return NO;
            }
            NSLog(@"return yes");
            
        }
    }
    
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

加扣群385378208即可下载工程源码

 

加扣群385378208即可下载工程源码

转载于:https://www.cnblogs.com/srf123/p/6133777.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值