AFN實現(xiàn)下載操作


- (void)download
{
    // 1.創(chuàng)建會話管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    // 2.創(chuàng)建請求對象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com/img/bd_logo1.png"]];

    //3.創(chuàng)建下載任務(wù)
    /*
     第一個參數(shù):請求對象
     第二個參數(shù):進度回調(diào) downloadProgress(獲得進度信息)
     第三個參數(shù):destination
                targetPath:文件的臨時存儲路徑
                response:響應(yīng)頭信息
                返回值:NSURL(AFN內(nèi)部已經(jīng)實現(xiàn)了文件剪切的過程,但是需要我們告訴他應(yīng)該把文件剪切到哪里)
     第四個參數(shù):completionHandler 請求完成的時候調(diào)用
                response:響應(yīng)頭信息
                filePath==fullPath 文件的最終目錄
                error:錯誤信息
     */
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

        NSLog(@"%f",1.0 *downloadProgress.completedUnitCount /downloadProgress.totalUnitCount);

    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];

        NSLog(@"---%@---\n%@",targetPath, fullPath);

        //NSLog(@"%@--%@",[NSURL URLWithString:fullPath],[NSURL fileURLWithPath:fullPath]);
        return [NSURL fileURLWithPath:fullPath];

    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

        NSLog(@"下載完成");
    }];

    //4.執(zhí)行方法
    [downloadTask resume];
}


參考鏈接
參考鏈接
參考鏈接

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

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

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