iOS网络基础第一篇





//----------------------TCNetworkBaseFirstViewController.h


#import <UIKit/UIKit.h>


@interface TCNetworkBaseFirstViewController : UIViewController


@end


//----------------------TCNetworkBaseFirstViewController.m



#import "TCNetworkBaseFirstViewController.h"

#import "FirstNetWorkObject.h"


@interface TCNetworkBaseFirstViewController ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate>


@end


@implementation TCNetworkBaseFirstViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    FirstNetWorkObject *firstNetwork = [[FirstNetWorkObject alloc]init];

    //普通网络请求

    NSString *urlString = @"http://www.atool.org/email_image.php";

    //--基础URL

    [firstNetwork doURLWith:urlString];

    //--同步请求

    [firstNetwork doSyncRequest:urlString];

    //--队列请求

    [firstNetwork doQueuedRequest:urlString delegate:nil];

    //--异步请求

    [firstNetwork startRequestWithURLString:urlString];

    

}

@end





//----------------------FirstNetWorkObject.h


#import <Foundation/Foundation.h>


@interface FirstNetWorkObject : NSObject


//TODO: URL

- (void)doURLWith:(NSString *)urlString;


//TODO:  同步请求

- (void)doSyncRequest:(NSString *)urlString;


//TODO: 队列异步请求

- (void)doQueuedRequest:(NSString *)urlString delegate:(id)delegate;


//TODO: 异步请求

- (void)startRequestWithURLString:(NSString *)urlString;


@end



//----------------------FirstNetWorkObject.m


#import "FirstNetWorkObject.h"

@interface FirstNetWorkObject()<NSURLConnectionDataDelegate>

{

    NSOperationQueue *_queue;

    NSURL *_url;

    NSURLConnection  *_connection;

}

@end


@implementation FirstNetWorkObject

//TODO: URL

- (void)doURLWith:(NSString *)urlString

{

    //---Base

    

    /*

     @ NSURL

     */

    NSURL *url = [NSURL URLWithString:urlString];

    if (url == nil) {

        NSLog(@"url is nil .");

        return;

    }

    NSLog(@"port: %@",url.port);

    NSLog(@"host: %@",url.host);

    NSLog(@"path: %@",url.path);

    /*

     @ NSURLRequest

     包含加载URL内容所需要的信息;

     支持HTTPHTTPSFTPFILE URL

     */

    //三种请求方式 - 利用 #define .... #ifdef ....  #else 区分

    //#define defaultRequest        //1 普通

    //#define defaultMutableRequest //2 自定义缓存与超时值创建request

    //#define requestBody           //3 设置Body

    

#ifdef defaultRequest        //-----1

    //系统默认

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

#else                        //-----1

#ifdef defaultMutableRequest //-----2

    //自定义缓存与超时值创建request

    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.f];

#else                        //-----2

    //NSMutableURLRequestNSURLRequest的字类,可修改请求属性

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];

    

#ifdef requestBody           //-----3

    [request setHTTPBody:[@"body" dataUsingEncoding:NSUTF8StringEncoding]];

#else                        //-----3

    //输入流(使用输入流提供请求体而无须将整个体加载到内存中)发送诸如照片、视频等大量内容的最佳选择

    NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:@"文件路径"];

    [request setHTTPBodyStream:inputStream];

    

#endif //3

#endif //2

#endif //1

    if (request == nil) {

        NSLog(@"request is nil .");

        return;

    }

}


//TODO:  同步请求

- (void)doSyncRequest:(NSString *)urlString

{

    NSURL *url = [NSURL URLWithString:urlString];

    

    //缓存策略:永不缓存

    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.f];

    NSHTTPURLResponse *response;

    NSError           *error = nil;

    

    

    /*

     NSURLConnection

     */

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    

    

    if (error) {

        NSLog(@"error on load = %@",[error localizedDescription]);

        return;

    }

    

    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {

        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

        if (httpResponse.statusCode != 200) {

            NSLog(@"code = %@",[NSNumber numberWithInteger:httpResponse.statusCode]);

            return;

        }

    }

    

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

    NSLog(@"%@",xml);

    

}


//TODO: 队列异步请求

- (void)doQueuedRequest:(NSString *)urlString delegate:(id)delegate

{

    NSURL *url = [NSURL URLWithString:urlString];

    

    //缓存策略:永不缓存

    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.f];

    if (!_queue) {

        _queue = [[NSOperationQueue alloc] init];

    }

    

    //    [_queue setMaxConcurrentOperationCount:2]; //设置并发操作个数

    //    [NSOperationQueue mainQueue];              //获取队列

    

    [NSURLConnection sendAsynchronousRequest:request queue:_queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        if (connectionError) {

            NSLog(@"error on load = %@",[connectionError localizedDescription]);

            return;

        }

        

        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {

            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

            if (httpResponse.statusCode != 200) {

                NSLog(@"code = %@",[NSNumber numberWithInteger:httpResponse.statusCode]);

                return ;

            }

        }

        

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

        NSLog(@"%@",xml);

    }];

}


//TODO: 异步请求

- (void)startRequestWithURLString:(NSString *)urlString

{

    _url = [NSURL URLWithString:urlString];

    NSURLRequest *request = [NSURLRequest requestWithURL:_url];

    _connection = [NSURLConnection connectionWithRequest:request delegate:self];

    [_connection start];

}


#pragma mark - Connection detegate


//TODO: NSURLConnectionDataDelegate


// 链接收到HTTP重定向响应时得到调用

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response

{

    NSLog(@"[ Redirect request for %@ redirection to %@ ]",_url,request.URL);

    NSLog(@"[ All headers = %@ ]",[(NSHTTPURLResponse *)response allHeaderFields]);

    return request;

}


// 服务器接收到请求时

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

    NSLog(@"all headers = %@",[httpResponse allHeaderFields]);

    

    if (httpResponse.statusCode != 200) {

        NSLog(@"code is not 200 .");

        [_connection cancel];

        return;

    }

}


//当收到服务器返回的数据时触发, 返回的可能是资源片段

static NSUInteger _totalDownload = 0;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    _totalDownload += [data length];

    NSLog(@"received %lu ",(unsigned long)_totalDownload);

}



// 请求数据失败时触发

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"%s load failed with error %@ ", __FUNCTION__,[error localizedDescription]);

}


//当服务器返回所有数据时触发, 数据返回完毕

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"did finish loading .");

}

@end




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值