AFNetworking 3.0 + 根据url下载文件

- (void)downFileFromServerWithUrlString:(NSString *)urlString{数据库

    

    NSURL *URL = [NSURL URLWithString:urlString];app

    

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];async

    

    //AFN3.0+基于封住URLSession的句柄ui

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];atom

    

    //请求url

    NSURLRequest *request = [NSURLRequest requestWithURL:URL];spa

    

    //下载Task操做.net

    _downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {component

        

        // @property int64_t totalUnitCount;  须要下载文件的总大小orm

        // @property int64_t completedUnitCount; 当前已经下载的大小

        

 

        // 回到主队列刷新UI

        dispatch_async(dispatch_get_main_queue(), ^{

            

            [HUD showAnimated:YES whileExecutingBlock:^{

                HUD.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;

            

            } completionBlock:^{

                

            }];

            

        });

        

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

        

        //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径

        

        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

        NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];

        return [NSURL fileURLWithPath:path];

        

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

        // filePath就是你下载文件的位置,你能够解压,也能够直接拿来使用

        

        //下载完成走这个block

        if (!error)

        {

            [HUD removeFromSuperview];

            HUD = nil;

            //若是请求没有错误(请求成功), 则打印地址

//            NSLog(@"%@", filePath);

//            NSLog(@"%@",filePath.path);

            

            NSData *data = [NSData dataWithContentsOfURL:filePath];

            

            NSArray *arr = [_downloadTask.response.suggestedFilename componentsSeparatedByString:@"."];

            

            NSString *behindStr = [NSString stringWithFormat:@"%@.%@",STR_OBJ([_wordArr objectAtIndex:_index][@"name"]),STR_OBJ([arr lastObject])];

            

            NSLog(@"%@",_downloadTask.response.suggestedFilename);

            //获取数据写入文件  写入文件须要注意每次app启动沙盒路径都是动态变化的  若是要作数据库存储不能直接存储完整的文件路径  只须要存储本身设定的表示字段  再每次获取时再动态获取完整路径

            [self writeToFileWithData:data WithFileName:behindStr];

            

        }else{

            

            [GlobelModel showTipToView:self.view andTipText:error.localizedDescription];

            

        }

        

//        NSString *imgFilePath = [filePath path];// 将NSURL转成NSString

//        

//        NSLog(@"%@",imgFilePath);

    

        

    }];

}

 

#pragma mark 将数据写入文件

 

- (void)writeToFileWithData:(NSData *)data WithFileName:(NSString *)fileName{

    

    //此处首先指定了图片存取路径(默认写到应用程序沙盒 中)

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

    

    //并给文件起个文件名

    NSString *path=[[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];

    NSLog(@"%@",path);

    BOOL isSuccess =  [data writeToFile:path atomically:NO];

    

    if (isSuccess) {

        

        //写入成功  存入数据库

        

        NSDictionary *dic = [_wordArr objectAtIndex:_index];//对于的数据源

        

        NSInteger idIndex = [dic[@"id"] integerValue];

        

        //插入数据

        

        BOOL isSuccess =  [[MySqlite sharedInstance].database executeUpdate:@"INSERT INTO WordList (uid, path) VALUES (?,?);",@(idIndex),fileName];

        

        if (isSuccess) {

            

            //插入成功  刷新tableview

            

            [_ruleSearchTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:_index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];

            

        }

        

    }

    

}

相关文章
相关标签/搜索