美文网首页iOS开发技术分享
NSURLConnection初体验(加载网络数据)

NSURLConnection初体验(加载网络数据)

作者: 不会打滚儿的狮子 | 来源:发表于2016-07-10 00:22 被阅读19次

    先来看一下效果图

    展示加载成功界面 if (connectionError) {失败后

    //  Created by 贺培勇 on 16/7/9.

    //  Copyright © 2016年 tcast. All rights reserved.

    #import "ViewController.h"

    @interface ViewController ()

    @end

    @implementation ViewController

    - (void)viewDidLoad {

    [super viewDidLoad];

    //创建URL

    NSURL * url = [NSURL URLWithString:@"http://www.sina.com.cn/"];

    //根据URL创建请求

    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];

    //设置请头属性

    [request setValue:@"iPhone AppleWebKit" forHTTPHeaderField:@"User-Agent"];

    __weak typeof(self) weakself = self;

    //连立连接,发送请求

    #pragma clang diagnostic push

    #pragma clang diagnostic ignored "-Wdeprecated-declarations"

    //将编译器提示-Wdeprecated-declarations警告的代码放在这里即可

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

    if (connectionError) {

    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"网络连接失败" message:@"是否重新加载" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

    [alertView show];

    return;

    }

    if (data == nil) {

    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"获取网络数据失败" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

    [alertView show];

    return;

    }

    //数据分析/数据反序列化

    NSString * restre = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

    //把数据显示到界面上

    UIWebView * webView = [[UIWebView alloc]init];

    webView.frame = weakself.view.bounds;

    [weakself.view addSubview:webView];

    //加载超文本数据并显示到UIWebView

    [webView loadHTMLString:restre baseURL:url];

    #pragma clang diagnostic pop

    }];

    - (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

    }

    @end

    相关文章

      网友评论

        本文标题:NSURLConnection初体验(加载网络数据)

        本文链接:https://www.haomeiwen.com/subject/tkhdjttx.html