你的位置:首页 > 操作系统

[操作系统]IOS 网络浅析-(三 NSURLConnection代理)


对于现在的iOS开发,用法简单,最古老最经典最直接的NSURLConnection的作用不是很大,但是作为一名ios开发者,我们应该拥有一颗热爱学习的心,下面通过代码的实现简单介绍一下NSURLConnection。

 

//// ViewController.m// CX- NSURLConnection//// Created by ma c on 16/3/17.// Copyright © 2016年 xubaoaichiyu. All rights reserved.//#import "ViewController.h"@interface ViewController ()<NSURLConnectionDataDelegate>@property (nonatomic, strong) NSMutableData * data;@end@implementation ViewController#pragma mark - life- (void)viewDidLoad {  [super viewDidLoad];    //data初始化,这个很简单,但是如果粗心大意很容易造成不必要的烦恼  self.data = [NSMutableData data];    NSString * urlString = [NSString stringWithFormat:@"http://localhost/tupian.jpg"];    //如果有中文,则不能正常运行,因此在这里进行处理。  //注意设置 ios为8 以下  urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    NSURL * url = [NSURL URLWithString:urlString];    NSURLRequest * request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];    NSURLConnection * connection = [NSURLConnection connectionWithRequest:request delegate:self];    //开启网络  [connection start];  }#pragma mark - deleDate//服务器返回消息-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{  NSLog(@"服务器返回消息");}//接受数据(多次调用)-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{    [self.data appendData:data];  }//请求完成-(void)connectionDidFinishLoading:(NSURLConnection *)connection{    NSLog(@"%@",self.data);    NSLog(@"请求完成");}//有序二进制代码过长,截取部分结果。/* 2016-03-17 21:15:15.699 CX- NSURLConnection[3175:173721] 服务器返回消息 2016-03-17 21:15:15.702 CX- NSURLConnection[3175:173721] <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe10058 45786966 00004d4d 002a0000 00080002 01120003 00000001 00010000 87690004 00000001 00000026 00000000 0003a001 00030000 00010001 0000a002 00040000 00010000 02eea003 00040000 00010000   a6845cde 3af7a697 f4aaead9 c8a70cd5 08ffd9> 2016-03-17 21:15:15.788 CX- NSURLConnection[3175:173721] 请求完成 */@end