//
// Connection.h
//
// Created by 毛连帅 on 14-6-24.
// Copyright (c) 2014年 毛帅. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef void(^FinishedBlock) (NSData *data);
@interface Connection : NSObject<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
@property (nonatomic,retain) NSMutableData * dataArray;
@property (nonatomic,copy) FinishedBlock finished;
// 直接调用这个类方法即可实现网络请求(注:URLStr表示需要传过来的网址)
+ (void)connectionGetWithURL:(NSString *)URLStr block:(FinishedBlock)block;
@end
//
// Connection.m
//
// Created by 毛连帅 on 14-6-24.
// Copyright (c) 2014年 毛帅. All rights reserved.
//
#import "Connection.h"
@implementation Connection
- (void)dealloc
{
[_dataArray release];
_dataArray = nil;
[super dealloc];
}
// 初始化网络对象
- (instancetype)init
{
self = [super init];
if (self) {
_dataArray = [[NSMutableData alloc] init];
}
return self;
}
// 获得网址并进行网络请求
+ (void)connectionGetWithURL:(NSString *)URLStr block:(FinishedBlock)block {
Connection * conn = [[Connection alloc] init];
conn.finished = block;
// 网络请求
[conn startGetWithUrl:URLStr];
[conn release];
}
// 开始网络请求
- (void)startGetWithUrl:(NSString *)url {
NSURL * currentUrl = [NSURL URLWithString:url];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:currentUrl];
// 设置网络请求方式
[request setHTTPMethod:@"GET"];
// 开始网络请求
[NSURLConnection connectionWithRequest:request delegate:self];
}
// 开始响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
}
// 接受二进制数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_dataArray appendData:data];
}
// 接受完成时运行
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// 返回数据
self.finished(_dataArray);
}
// 异常时运行
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"网络连接异常");
}
@end