您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

封裝 NSURLRequest:用 Block 回呼打造可快取的網路請求層

編輯:iOS 開發綜合

用 NSURLRequest 發請求的固定流程是四步:建立 NSURL、建立 NSURLRequest、呼叫 connectionWithRequest:delegate:、實作 NSURLConnectionDataDelegate。每次要發請求就重複這一套,顯然可以更省事。以下示範如何封裝成一個帶 Block 回呼、支援本地快取的請求層。

MyUrlRequest.h

@interface MyUrlRequest : NSObject <NSURLConnectionDataDelegate>
{
    NSMutableData *_mData;   // 累積接收到的資料
}

@property (nonatomic, copy) NSString *urlStr;
@property (nonatomic, copy) void (^finishBlock)(NSData *data);   // 成功回呼
@property (nonatomic, copy) void (^failedBlock)();                // 失敗回呼
@property (nonatomic, assign) BOOL isCache;                       // 是否啟用快取

- (void)startRequest;
@end

MyUrlRequest.m

#import "MyUrlRequest.h"
#import "NSString+Hashing.h"

@implementation MyUrlRequest

@synthesize urlStr;
@synthesize finishBlock;
@synthesize failedBlock;
@synthesize isCache;

- (id)init {
    if (self = [super init]) {
        _mData = [[NSMutableData alloc] init];
    }
    return self;
}

- (void)startRequest {
    //  manager 中的 autorelease 可能在方法結束後才發生,
    // 因此這裡先 retain 以確保自身存活到請求結束
    [self retain];

    if (self.isCache) {
        NSString *path = [NSHomeDirectory()
            stringByAppendingFormat:@"/tmp/%@", [self.urlStr MD5Hash]];
        NSFileManager *manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath:path]) {
            NSData *data = [NSData dataWithContentsOfFile:path];
            self.finishBlock(data);
            [self release];
            return;
        }
    }

    NSURL *url = [NSURL URLWithString:self.urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

#pragma mark - NSURLConnectionDataDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_mData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [self release];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

    if (self.isCache) {
        NSString *path = [NSHomeDirectory()
            stringByAppendingFormat:@"/tmp/%@", [self.urlStr MD5Hash]];
        [_mData writeToFile:path atomically:YES];
    }
    self.finishBlock(_mData);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [self release];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    self.failedBlock();
}

- (void)dealloc {
    [_mData release];
    self.finishBlock = nil;
    self.failedBlock = nil;
    [super dealloc];
}

@end

MyRequestManager.h

#import <Foundation/Foundation.h>
#import "MyUrlRequest.h"

@interface MyRequestManager : NSObject

+ (void)requestWithUrl:(NSString *)urlString
             andIsCache:(BOOL)isCache
                 finish:(void (^)(NSData *data))finishBlock
                 failed:(void (^)())failedBlock;

@end

MyRequestManager.m

#import "MyRequestManager.h"

@implementation MyRequestManager

+ (void)requestWithUrl:(NSString *)urlString
            andIsCache:(BOOL)isCache
                finish:(void (^)(NSData *data))finishBlock
                failed:(void (^)())failedBlock {
    MyUrlRequest *request = [[[MyUrlRequest alloc] init] autorelease];
    request.urlStr      = urlString;
    request.isCache     = isCache;
    request.finishBlock = finishBlock;
    request.failedBlock = failedBlock;

    // 送出 startRequest 後此類別方法即結束,
    // autorelease 可能隨之發生,因此在 startRequest 內部才 retain
    [request startRequest];
}

@end

呼叫方式

[MyRequestManager requestWithUrl:urlString
                      andIsCache:YES
                          finish:^(NSData *data) {
                              // 在回呼中處理資料
                          }
                          failed:^{
                              NSLog(@"請求失敗");
                          }];

這個封裝的取捨與改進空間

這個設計用「請求物件自己 retain 自己、結束後 release」的手法解決了非同步生命週期問題,思維很巧妙,但也埋了風險:任何一條提前 return 的路徑都必須記得 release,否則就是洩漏。我在快取命中的分支中補上了 release,這正是原寫法容易遺漏的地方。

若要在正式專案中沿用同樣的封裝思路,建議做幾點調整:

  • 改用 ARC,把生命週期交給編譯器,並用 __block 或 weak 化的方式避免 Block 捕獲 self 造成循環參照。
  • 把快取路徑從 tmp/ 改到 Caches 目錄。tmp 隨時可能被系統清空,而快取通常希望活得久一些;Caches 則是系統在空間不足時才會回收。
  • 快取檔名直接用 URL 的 MD5 有碰撞風險,實務上會再加上雜湊或改用 SHA,並一併記錄過期時間。
  • NSURLConnection 已被蘋果標記為 deprecated,新專案請改用 NSURLSession。它的 dataTaskWithRequest:completionHandler: 本來就是 Block 風格,封裝成本反而更低,也內建背景傳輸與快取策略控制。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved