iOS网络操作基础 - NSURLConnection的基本使用(GET)

学习了关于iOS开发中网络操作NSURLConnection的基本用法(GET方法),记录下笔记。
学习阶段,如果哪部分有问题,欢迎指正,共同探讨。@Apach3


GET方法:从服务器获取一段内容,通常不包含请求体

发送请求的三个步骤:
- 创建请求路径
- 创建请求对象
- 发送网络请求

和网络请求相关的文件:
- NSURL(客户端用来访问哪台服务器的指定资源)
- NSURLRequest(客户端用来发起网络请求的内容)
- NSURLConnection(客户端与服务器之间建立的网络连接)
- NSURLResponse(服务端给予客户端的响应结果)


新建Xcode工程,选择Single View Application,语言为Objective-C。文件夹目录如下:
文件夹目录


下面是相关文件代码:

ViewController.h:

//
//  ViewController.m
//  WebRequest
//
//  Created by APACHE on 2017/10/23.
//  Copyright © 2017年 APACHE. All rights reserved.
//

#import "ViewController.h"
#import "CustomView.h"

@interface ViewController () <NSURLConnectionDataDelegate, NSURLConnectionDelegate> {
    NSMutableData *receiveData;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    self.view.backgroundColor = [UIColor lightGrayColor];
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //1.表示访问的服务器,创建请求路径
    //              http:// hostName : port / absoltuePath ? (query)key=value&key2=value2
    //只有GET请求将请求参数拼接在后面
    NSURL *url = [NSURL URLWithString:@"http://c.3g.163.com/nc/video/list/VAP4BFE3U/y/0-10.html"];

    //2.创建请求对象,表示客户端发起的网络请求的请求内容(默认是GET请求)
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    //3.发送请求,客户端与服务器之间的网络连接
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    //启动网络请求(必须是联网状态)
    [connection start];
}

//NSURLResponse 网络请求的响应结果
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response {
//    NSLog(@"%@", response);
    /*
     控制台输出:App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
     iOS9中新增App Transport Security(简称ATS)特性强制使用HTTPS,提升安全级别。
     解决办法:info.plist文件新增如下键值属性:
     NSAppTransportSecurity      Dictionary      (1 item)
     NSAllowsArbitraryLoads      Boolean         YES
     服务端响应客户端的状态码为200标示本次发起的网络请求是成功的。
     */
}

//用来接收网络响应数据 多次调用的
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //如果没有 则初始化
    if (!receiveData) {
        receiveData = [[NSMutableData alloc] init];
    }
    [receiveData appendData:data];
}

//网络请求结束
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    id obj = [NSJSONSerialization JSONObjectWithData:receiveData options:0 error:nil];
    if ([obj isKindOfClass:[NSDictionary class]]) {
        id allNews = [(NSDictionary *)obj objectForKey:@"VAP4BFE3U"];
        for (int i=0; i<[(NSArray *)allNews count]; i++) {
            NSString *title = [(NSDictionary *)[(NSArray *)allNews objectAtIndex:i] objectForKey:@"title"];
            NSString *ptime = [(NSDictionary *)[(NSArray *)allNews objectAtIndex:i] objectForKey:@"ptime"];
            NSString *topicDesc = [(NSDictionary *)[(NSArray *)allNews objectAtIndex:i] objectForKey:@"topicDesc"];
            CustomView *newView = [[CustomView alloc] initWithFrame:CGRectMake(0, 30+i*65, self.view.frame.size.width, 60)];
            [newView setTitle:title andPtime:ptime andTopicDesc:topicDesc];
            [self.view addSubview:newView];
        }
    }
}

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


@end

CustomView.h&CustomView.m:

//
//  CustomView.h
//  WebRequest
//
//  Created by APACHE on 2017/10/23.
//  Copyright © 2017年 APACHE. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface CustomView : UIView

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *ptimeLabel;
@property (nonatomic, strong) UILabel *topicDescLabel;

- (void)setTitle:(NSString *)title andPtime:(NSString *)ptime andTopicDesc:(NSString *)topicDesc;

@end




//
//  CustomView.m
//  WebRequest
//
//  Created by APACHE on 2017/10/23.
//  Copyright © 2017年 APACHE. All rights reserved.
//

#import "CustomView.h"

#define viewWidth self.frame.size.width
#define viewHeight self.frame.size.height

@implementation CustomView

- (instancetype)initWithFrame:(CGRect)frame {
    //    self = [super init];
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];

        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, viewWidth, viewHeight/3)];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.font = [UIFont boldSystemFontOfSize:16];
        _titleLabel.textAlignment = NSTextAlignmentLeft;
        [self addSubview:_titleLabel];

        _ptimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, viewHeight/3, viewWidth, viewHeight/3)];
        _ptimeLabel.textColor = [UIColor redColor];
        _ptimeLabel.font = [UIFont boldSystemFontOfSize:19];
        _ptimeLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_ptimeLabel];

        _topicDescLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, viewHeight/3*2, viewWidth, viewHeight/3)];
        _topicDescLabel.textColor = [UIColor blackColor];
        _topicDescLabel.font = [UIFont boldSystemFontOfSize:13];
        _topicDescLabel.textAlignment = NSTextAlignmentLeft;
        [self addSubview:_topicDescLabel];
    }
    return self;
}

- (void)setTitle:(NSString *)title andPtime:(NSString *)ptime andTopicDesc:(NSString *)topicDesc {
    _titleLabel.text = title;
    _ptimeLabel.text = ptime;
    _topicDescLabel.text = topicDesc;
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end

收到的数据如下所示,为字典嵌套数组再嵌套字典:
这里写图片描述
模拟器情况:
模拟器情况


加油!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值