AFNetworking下載文件

AFN下載可以分為三個(gè)部分,初始化sessionManage對(duì)象,設(shè)置下載地址和儲(chǔ)存路徑,下載進(jìn)度

初始化對(duì)象

/* 創(chuàng)建網(wǎng)絡(luò)下載對(duì)象 */
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

設(shè)置下載地址和儲(chǔ)存路徑

NSString * urlStr = [NSString stringWithFormat:@"http://files.lqfast.com:8030/xxxxx"];
/* 下載地址 */
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
/* 下載路徑 */
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Announcement"];
NSString *filePath = [path stringByAppendingPathComponent:url.lastPathComponent];

其中@"Documents/Announcement"是指定下載到沙盒下Announcement文件夾中,Announcement文件是自己創(chuàng)建的,創(chuàng)建方法 iOS中在沙盒中創(chuàng)建文件夾

下載進(jìn)度

/* 開(kāi)始請(qǐng)求下載 */
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
    NSLog(@"下載進(jìn)度:%.0f%", downloadProgress.fractionCompleted * 100);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
    dispatch_async(dispatch_get_main_queue(), ^{
        //如果需要進(jìn)行UI操作,需要獲取主線程進(jìn)行操作
    });
    /* 設(shè)定下載到的位置 */
    return [NSURL fileURLWithPath:filePath];
            
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
     NSLog(@"下載完成");
     [self extract];
}];
 [downloadTask resume];

至此,一個(gè)基于AFNetworking的文件下載就OK了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容