• 热门专题

iOS中UIWebView加载网络数据技术分享

作者:  发布日期:2015-11-04 19:38:46
Tag标签:数据  技术  网络  
  • 直奔核心:

     

    #import "TechnologyDetailViewController.h"
    #define kScreenWidth [UIScreen mainScreen].bounds.size.width
    #define kScreenHeight [UIScreen mainScreen].bounds.size.height
    @interface TechnologyDetailViewController ()
    @property (nonatomic,retain)UIWebView *webView;//显示详情页面
    @end

    @implementation TechnologyDetailViewController
    - (void)dealloc
    {
        self.webView = nil;
        self.ids = nil;
        [super dealloc];
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        //设置背景
        self.view.backgroundColor = [UIColor yellowColor];
        //调用请求网络数据
        [self readDataFromNetWork];
        //    self.automaticallyAdjustsScrollViewInsets = NO;
        [self.view addSubview:self.webView];
    }

     

    懒加载UIWebView

    //懒加载
    - (UIWebView *)webView{
        if (!_webView) {
            self.webView = [[[UIWebView alloc]initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)]autorelease];
            self.webView.backgroundColor = [UIColor orangeColor];
            
        }
        return [[_webView retain ]autorelease];
    }


    核心代码如下:

     

    //解析数据
    - (void)readDataFromNetWork{
        NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html",self.ids];
        NSURL *url = [NSURL URLWithString:str];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            
            NSString *body = dic[self.ids][@"body"];
            NSString * title = dic[self.ids][@"title"];
            NSString *digest = dic[self.ids][@"digest"];
            NSString *ptime = dic[self.ids][@"ptime"];
            NSString * source = dic[self.ids][@"source"];
            NSArray * img = dic[self.ids][@"img" ] ;
            //        NSLog(@"%@",img);
            if (img.count) {
                for (int i = 0; i < img.count; i ++) {
                    
                    
                    NSString *imgString = [NSString stringWithFormat:@"<p style="text-align:center"><img src="%@" /></p>",img[i][@"src"]];
                    NSLog(@"imString  = %@",imgString);
                    
                    imgString = [imgString stringByReplacingOccurrencesOfString:@"<!--IMG#%d-->" withString:imgString];
                    body = [imgString stringByAppendingString:body];
                    
                    
                }
            }
            //        NSLog(@"body =  %@",body);
            
            //借助第三方进行排版
            NSString *filePath = [[NSBundle mainBundle]pathForResource:@"topic_template" ofType:@"html"];
            NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
            
            htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__BODY__" withString:body];
            htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__TITLE__" withString:title];
            htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__AUTHOR__" withString:source];
            htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__DIGEST__" withString:digest];
            htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__TIME__" withString:ptime];
            htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__PTIME__" withString:ptime];
            [self.webView loadHTMLString:htmlString baseURL:nil];
            
            
        }];
        
    }

     

    ======================================================================================================

    实在看不懂再看下demol例子:

     

    UIWebView的loadRequest可以用来加载一个url地址,它需要一个NSURLRequest参数。我们定义一个方法用来加载url。在UIWebViewDemoViewController中定义下面方法:

     

    - (void)loadWebPageWithString:(NSString*)urlString
    {
        NSURL *url =[NSURL URLWithString:urlString];
        NSLog(urlString);
        NSURLRequest *request =[NSURLRequest requestWithURL:url];
        [webView loadRequest:request];
    }


     

    在界面上放置3个控件,一个textfield、一个button、一个uiwebview,布局如下:

    在代码中定义相关的控件:webView用于展示网页、textField用于地址栏、activityIndicatorView用于加载的动画、buttonPress用于按钮的点击事件。

     

    @interface UIWebViewDemoViewController :UIViewController<UIWebViewDelegate> {   
        IBOutlet UIWebView *webView;
        IBOutlet UITextField *textField;
        UIActivityIndicatorView *activityIndicatorView;
         
    }
    - (IBAction)buttonPress:(id) sender;
    - (void)loadWebPageWithString:(NSString*)urlString;
    @end


     

    使用IB关联他们。

    设置UIWebView,初始化UIActivityIndicatorView:

     

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        webView.scalesPageToFit =YES;
        webView.delegate =self;
        activityIndicatorView = [[UIActivityIndicatorView alloc] 
                                 initWithFrame : CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)] ;
        [activityIndicatorView setCenter: self.view.center] ;
        [activityIndicatorView setActivityIndicatorViewStyle: UIActivityIndicatorViewStyleWhite] ; 
        [self.view addSubview : activityIndicatorView] ;
        [self buttonPress:nil];
        // Do any additional setup after loading the view from its nib.
    }


     

    UIWebView主要有下面几个委托方法:

    1、- (void)webViewDidStartLoad:(UIWebView *)webView;开始加载的时候执行该方法。
    2、- (void)webViewDidFinishLoad:(UIWebView *)webView;加载完成的时候执行该方法。
    3、- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;加载出错的时候执行该方法。

    我们可以将activityIndicatorView放置到前面两个委托方法中。

     

    - (void)webViewDidStartLoad:(UIWebView *)webView
    {
        [activityIndicatorView startAnimating] ;
    }
    - (void)webViewDidFinishLoad:(UIWebView *)webView
    {
        [activityIndicatorView stopAnimating];
    }


     

    buttonPress方法很简单,调用我们开始定义好的loadWebPageWithString方法就行了:

     

    - (IBAction)buttonPress:(id) sender
    {
        [textField resignFirstResponder];
        [self loadWebPageWithString:textField.text];
         
    }


     

    当请求页面出现错误的时候,我们给予提示:

    - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
    {
        UIAlertView *alterview = [[UIAlertView alloc] initWithTitle:@"" message:[error localizedDescription]  delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alterview show];
        [alterview release];
    }


    总结:本文通过实现一个简单的浏览器,说明了uiwebview的方法和属性,相信通过这个例子,应该明白uiwebview的使用了。

     

    有疑问可通过新浪微博私信给我:http://weibo.com/hanjunqiang

     

About IT165 - 广告服务 - 隐私声明 - 版权申明 - 免责条款 - 网站地图 - 网友投稿 - 联系方式
本站内容来自于互联网,仅供用于网络技术学习,学习中请遵循相关法律法规
极速时时彩yko| 7us| ii7| qag| u7e| gck| 7ya| ym8| iwu| iec| a8a| ieq| 6qq| yw6| eyw| w6y| uua| m7y| agm| 7ww| oc7| omw| gqg| c7u| aaq| 5wu| qe6| iww| i6s| cec| 6aw| ya6| kyi| a6e| uuc| 7mu| 5wu| sc5| cyw| w5y| uus| 5ao| sc5| oou| i6m| qki| c6e| ssq| 4ek| 4yo| km4| qyo| k4i| ioy| 5ua| sk5| uio| m5s| cek| 5ay| ay3| qw3| kek| o4s| kig| 4us| ik4| ess| k4i| qiq| 4mk| wy2| gqc| a33| sq3| wyg| u3q| kgy| 3yo| kq3| sak| c3i| mag| 4om| wy2| eao| o2s| iwc| ces| 2ge|