美文网首页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初体验(加载网络数据)

    先来看一下效果图 // Created by 贺培勇 on 16/7/9. // Copyright © 2016...

  • YYKit__ YYWebImage__源码分析

    底层使用NSUrlConnection方式,多线程异步加载网络图片; 加载时先从内存缓存区寻找,再从磁盘缓存区寻找...

  • 网络

    NSURLConnection NSURLSession 普通网络请求 JSON数据解析 JSON序列化 数据解析...

  • iOS网络——检测手机网络状态Reachability

    一、整体介绍 前面已经介绍了网络访问的NSURLSession、NSURLConnection,还有网页加载有关的...

  • NSURLSSion和NSURLConnection

    NSURLConnection系统原生的对网络数据的请求 使用NSURLSession做网络请求 NSURLSes...

  • NSURLConnection和NSURLSession

    NSURLConnection和NSURLSession都是网络请求类! 它们都可以实现数据请求和上传数据。 NS...

  • IOS网络编程

    IOS网络编程 NSURLConnection NSURLSession是NSURLConnection 的替代者...

  • Paging3简单使用

    paging3有3种使用方式。 从数据库加载页面 从网络加载页面 从网络和数据库加载页面 1.从数据库加载页面 首...

  • 网络 NSURLConnection

    NSURL:请求地址 NSURLRequest:一个NSURLRequest对象就代表一个请求,它包含的信息有一个...

  • 06-网络(1)

    0712NSURLConnection 基本概念(01-网络的基本概念) Http是网络数据传输格式,TCP(UD...

网友评论

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

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