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

iOS 開發實戰:ASIHTTPRequest 網絡請求使用詳解

編輯:iOS 開發綜合

ASI 簡介

ASIHTTPRequest 是一款功能強大的第三方網絡請求庫,支援同步/異步請求、文件上傳下載、斷點續傳與進度監聽等。以下透過實例說明常見用法。

#import "ViewController.h"
#import "ASIHTTPRequest.h"

@interface HMViewController ()
@property (nonatomic, strong) ASIHTTPRequest *request;
@end

@implementation HMViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self asynGet];
}

請求的代理方法

#pragma mark - ASIHTTPRequestDelegate
// 1. 開始發送請求
- (void)requestStarted:(ASIHTTPRequest *)request {
    NSLog(@"requestStarted");
}

// 2. 接收到伺服器的響應頭
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders {
    NSLog(@"didReceiveResponseHeaders");
}

// 4. 響應數據接收完畢
- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"requestFinished--%@", [request responseData]);
}

// 5. 請求失敗
- (void)requestFailed:(ASIHTTPRequest *)request {
    NSLog(@"requestFailed");
}

異步 GET 請求

- (void)asynGet {
    NSURL *url = [NSURL URLWithString:@"https://localhost:8080/MJServer/video"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.timeOutSeconds = 15; // 15 秒未響應即超時
    request.delegate = self;
    [request startAsynchronous]; // 異步發送
    self.request = request;
}

- (void)dealloc {
    // 防止控制器銷毀後 request 回調代理導致野指針
    [self.request clearDelegatesAndCancel];
}

同步 GET 請求

- (void)synGet {
    NSURL *url = [NSURL URLWithString:@"https://localhost:8080/Server/video"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.timeOutSeconds = 15;
    // 這行代碼會阻塞,等待伺服器返回數據
    [request startSynchronous];

    NSError *error = [request error];
    if (error) {
        NSLog(@"請求失敗---%@", error);
    } else {
        NSData *data = [request responseData];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"請求成功---%@", dict);
    }
}

使用 Block 監聽請求

除了代理,ASI 還支援 block 與自定義選擇器兩種監聽方式:

- (void)asyncBlock {
    NSURL *url = [NSURL URLWithString:@"https://localhost:8080/Server/video"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startAsynchronous];

    // 設置 block 監聽
    [request setStartedBlock:^{ NSLog(@"setStartedBlock"); }];
    [request setHeadersReceivedBlock:^(NSDictionary *responseHeaders) { NSLog(@"headers--%@", responseHeaders); }];
    [request setDataReceivedBlock:^(NSData *data) { NSLog(@"data--%@", data); }];
    [request setCompletionBlock:^{ NSLog(@"setCompletionBlock"); }];
    [request setFailedBlock:^{ NSLog(@"setFailedBlock"); }];
}

// 自定義選擇器監聽
- (void)customSelector {
    NSURL *url = [NSURL URLWithString:@"https://localhost:8080/MJServer/video"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startAsynchronous];
    request.delegate = self;
    [request setDidStartSelector:@selector(start:)];
    [request setDidFinishSelector:@selector(finish:)];
}

- (void)start:(ASIHTTPRequest *)request { NSLog(@"start--%@", request); }
- (void)finish:(ASIHTTPRequest *)request {
    NSLog(@"finish--%d %@", [request responseStatusCode], [request responseData]);
}

文件下載(支援斷點續傳)

- (void)download {
    if (self.downloading) {
        [self.request clearDelegatesAndCancel];
        self.downloading = NO;
    } else {
        NSURL *url = [NSURL URLWithString:@"https://localhost:8080/Server/resources/test.mp4"];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

        // 設置文件緩存路徑
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        request.downloadDestinationPath = [caches stringByAppendingPathComponent:@"test.mp4"];

        // 進度監聽代理
        request.downloadProgressDelegate = self.progressView;
        // 支持斷點下載
        request.allowResumeForFileDownloads = YES;
        // 斷點續傳需設置臨時文件路徑
        request.temporaryFileDownloadPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"test.temp"];

        [request startAsynchronous];
        self.request = request;
        self.downloading = YES;
    }
}

- (void)setProgress:(float)newProgress {
    self.progressView.progress = newProgress;
}

文件上傳

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSURL *url = [NSURL URLWithString:@"https://localhost:8080/Server/upload"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

    // 設置普通參數
    [request setPostValue:@"zhangsan" forKey:@"username"];
    [request setPostValue:@"123" forKey:@"pwd"];
    [request setPostValue:@"28" forKey:@"age"];

    // 設置文件參數(ASI 會自動識別 MIMEType)
    NSString *file = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp4"];
    [request setFile:file forKey:@"file"];

    // 上傳進度監聽
    request.uploadProgressDelegate = self.progressView;

    [request startAsynchronous];

    // 監聽完成
    __weak typeof(request) weakRequest = request;
    [request setCompletionBlock:^{
        NSLog(@"%@", [weakRequest responseString]);
    }];
}

總結來說,ASI 的強大之處在於:透過 downloadProgressDelegate/uploadProgressDelegate 輕鬆實現進度條,透過 allowResumeForFileDownloads 與 temporaryFileDownloadPath 支持斷點續傳,並同時提供代理、block、自定義選擇器三種靈活的回調方式,滿足各種網絡請求場景的需求。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved