URL网络数据请求时,一般在项目中可书写两种方法比较好点,因为在项目中有时候会block更加方便或者和代理方式也更方便,这得视情况而定。
创建一个GetNewsData类 里面包含的两种获取网络数据的方式,
第1种,在别的地方调用使用block回调方法,返回数据;
第2种,是自定义代理方法返回数据给代理,只要其他类实现协议,并且做了GetNewsData类的代理和实现代理方法即可获取数据;
第一步、定义block回调函数的别名
typedef void (^GetNewsDataArray)(NSArray *array,NSString *error);
<span style="font-size:18px;">第二步、实现网络请求协议NSURLConnectionDataDelegate、定义GetNewsDataArray属性和声明网络请求方法(最好是类方法)</span>
<span style="font-size:12px;">@protocol GetNewsDataDelegate <NSObject><span style="font-family: Arial, Helvetica, sans-serif;">@optional</span><span style="font-family: Arial, Helvetica, sans-serif;">//获取新闻简要信息</span></span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:12px;">-(void)getNewsDataNewsDigests:(NSArray)arry Error:(NSString*)error;</span></span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:12px;">@end</span></span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:12px;">@interface GetNewsData : NSObject <NSURLConnectionDataDelegate></span></span>
<span style="font-size:12px;">// 使用代理方式</span>
<span style="font-size:12px;">- (void)requestDataByURLString:(NSString *)urlString;</span>
<span style="font-size:12px;">// 使用block回调方式</span>
<span style="font-size:12px;"><span style="font-family: Arial, Helvetica, sans-serif;">@property(nonatomic,strong)GetNewsDataArray getNewsDataArray;</span><span style="font-family: Arial, Helvetica, sans-serif;">//定义请求方法为静态方法,方便其他地方调用</span></span>
+(void)requestDataByURLString:(NSString *)urlString ByGetNewsDataArray:(GetNewsDataArray)getNewsDataArray
第三步、在.m文件中写出具体方法
#import "GetNewsData.h"
@interface GetNewsData ()
{
NSURLCache *_cache;
NSMutableURLRequest *_request;
NSURLConnection *_connection;
}
@end
@implementation GetNewsData
- (void)requestDataByURLString:(NSString *)urlString
{
// 1 URL
NSURL *url =[NSURL URLWithString:urlString];
// 2 缓存
_cache = [NSURLCache sharedURLCache];
[_cache setMemoryCapacity:4*1024*1024];
// 缓存与什么不同再请求协议请求数据 NSURLRequestReloadIgnoringLocalCacheData
_request = [[NSMutableURLRequestalloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:30];
// 3 链接服务器下载数据
_connection = [[NSURLConnectionalloc]initWithRequest:_requestdelegate:self];
// 4 开始连接
[_connection start];
}
// 类方法请求数据
+(void)requestDataByURLString:(NSString *)urlString ByGetNewsDataArray:(GetNewsDataArray)getNewsDataArray
{
GetNewsData *getNewsData = [GetNewsData new];
getNewsData.getNewsDataArray = getNewsDataArray;
[getNewsData requestDataByURLString:urlString];
}
#pragma mark -获取服务器响应-
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.newsData = [NSMutableDatadata];
}
#pragma mark -接收数据-
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.newsData appendData:data];
}
#pragma mark -请求成功-
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 请求到的大字典
NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:self.newsDataoptions:NSJSONReadingMutableLeaveserror:nil];
// 将字典里面的数组放到arry上
NSArray *arry = [NSArray arrayWithObject: dict[@"T1348648517839"]];
// 把大数组里面的每个字典都装到temp里面
NSMutableArray *temp = [NSMutableArrayarray];
for(NSDictionary *itemin arry)
{
NewsDigest *newsDigest = [NewsDigestnewsDigestWithDict:item];
[temp addObject:newsDigest];
}
// 这是自定义的方法,将请求数据传输给代理
if([self.delegaterespondsToSelector:@selector(getNewsDataNewsDigests:Error:)])
{
if(temp)
{
[self.delegategetNewsDataNewsDigests:tempError:nil];
}
else
{
[self.delegategetNewsDataNewsDigests:nilError:@"arr是空的!"];
}
}
// 这是block的回调,将数据传出去
// 判断是否block是否为空,这里的判断是不可缺少的,否则容易出错
if(self.getNewsDataArray)
{
if(temp)
{
self.getNewsDataArray(temp,nil);
}else
{
self.getNewsDataArray(nil,@"arr是空的!");
}
}
}
// 请求失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
if(error)
{
#warning 断网
#pragma mark --没有网络连接,加载缓存中的数据
NSCachedURLResponse *cacheResponse = [_cachecachedResponseForRequest:_request];
if (cacheResponse) {
NSLog(@"有缓存输出");
[_requestsetCachePolicy:NSURLRequestReturnCacheDataDontLoad];
_connection = nil;
// 链接服务器下载数据
NSURLConnection *urlConnection = [[NSURLConnectionalloc]initWithRequest:_requestdelegate:self];
_connection = urlConnection;
[_connection start];
}
// 这是自定义的方法,将请求数据传输给代理
if([self.delegaterespondsToSelector:@selector(getNewsDataNewsDigests:Error:)])
{
[self.delegategetNewsDataNewsDigests:nilError:@"网络请求失败!"];
}
// 这是block的回调,将数据传出去
// 判断是否block是否为空,这里的判断是不可缺少的,否则容易出错
if(self.getNewsDataArray)
{
self.getNewsDataArray(nil,@"网络请求失败!");
}
}
}
第四步、使用此类的方法
1.block方式
[GetNewsData requestDataByURLString:self.name ByGetNewsDataArray:^(NSArray *array, NSString *error) {
if(error == nil)
{
self.newsDigests = [NSMutableArray arrayWithArray:array];
}else
{
NSLog(@"请求数据失败");
}
}];
2. 代理方式