从服务器逐个下载文件

时间:2017-02-13 06:20:42

标签: ios objective-c uitableview

我必须从UITableViewCell中的相应按钮点击服务器上下载文件。当用户点击按钮以便在一个单元格中下载时,应该开始下载。完成下载后我将保存核心数据。这就是全部去了但是当下载当前文件时,如果用户点击下载Cell中的另一个文件,它也应该下载然后保存到核心数据并可用于播放。我在每个表格单元格中有不同的URL。如果用户点击多个按钮应该下载它们并保存到核心数据。这是我的代码。

            NSString *url=[[chatHistoryArr objectAtIndex:sender.tag]valueForKey:@"voice"];
        NSLog(@"%@",url);
        //NSURL *voiceUrl=[NSURL URLWithString:url];

        tempDict=[[NSMutableDictionary alloc]init];

        [tempDict setValue:[[chatHistoryArr objectAtIndex:sender.tag]valueForKey:@"msg_id"] forKey:@"msg_id"];
        [tempDict setValue:[[chatHistoryArr objectAtIndex:sender.tag]valueForKey:@"to"] forKey:@"to"];
        [tempDict setValue:[[chatHistoryArr objectAtIndex:sender.tag]valueForKey:@"from"] forKey:@"from"];
        [tempDict setValue:[[chatHistoryArr objectAtIndex:sender.tag]valueForKey:@"time"] forKey:@"time"];

        UIImageView* animatedImageView = [[UIImageView alloc] initWithFrame:cell.playButton.bounds];
        animatedImageView.animationImages = [NSArray arrayWithObjects:
                                             [UIImage imageNamed:@"1.png"],
                                             [UIImage imageNamed:@"2.png"],
                                             [UIImage imageNamed:@"3.png"],
                                             [UIImage imageNamed:@"4.png"], nil];
        animatedImageView.animationDuration = 3.0f;
        animatedImageView.animationRepeatCount = 10;
        [animatedImageView startAnimating];
        [cell1.playButton addSubview: animatedImageView];

        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
        // manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/octet-stream",@"video/3gpp",@"audio/mp4",nil];
        NSURL *URL = [NSURL URLWithString:url];
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];

        NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error)
            {
                NSLog(@"Error: %@", error);
            } else
            {

                NSData *data=[[NSData alloc]initWithData:responseObject];

            //Here I'm saving file to local storage then updating UI.
                    [self sentMsgSaveWithData:data orUrl:@"" withBool:YES withMsg_ID:@"" withDict:tempDict];

            }
        }];
        [dataTask resume];

在这里,我设法一次只下载一个文件,完成后如果用户点击另一个单元格,那么我只能下载它。但是我必须在Cell中的多个按钮点击下载多个文件。 我一直在努力实现这个。请给出一些建议 提前致谢。

1 个答案:

答案 0 :(得分:0)

在MVC模式中,cell是一个视图,不应该处理数据解析和下载。最好在你的模型中做到这一点。但简单来说,它通常放在控制器中。

  1. 将模型数组保存在控制器中并将数据传递给单元格
  2. 将单元格的按钮操作配置为控制器(委托或阻止或通知......)
  3. 将下载代码放入控制器并更新模型状态,并在完成后重新加载tableView。
  4. cell.h

    #import <UIKit/UIKit.h>
    #import "YourCellProtocol.h"
    
    typedef NS_ENUM(NSInteger, YourCellStatus) {
        YourCellStatusNormal,
        YourCellStatusDownloading,
        YourCellStatusCompleted
    };
    
    @interface YourCell : UITableViewCell
    
    @property (nonatomic, weak) id<YourCellProtocol> delegate;
    
    @property (nonatomic, assign) YourCellStatus status;
    
    @property (nonatomic, weak) id yourDataUsedToShownInUI;
    
    @end
    

    cell.m

    #import "YourCell.h"
    
    @interface YourCell ()
    
    @property (nonatomic, strong) UIButton *myButton;
    
    @end
    
    @implementation YourCell
    
    - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
        if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
            // init all your buttons etc
            _myButton = [UIButton buttonWithType:UIButtonTypeSystem];
            [_myButton addTarget:self action:@selector(myButtonPressed) forControlEvents:UIControlEventTouchUpInside];
            [self.contentView addSubview:_myButton];
        }
        return self;
    }
    
    - (void)setStatus:(YourCellStatus)status {
        //update your cell UI here
    }
    
    - (void)myButtonPressed {
        // tell your controller to start downloading
        if (self.status != YourCellStatusNormal) {
            [self.delegate didPressedButtonInYourCell:self];
        }
    }
    
    @end
    

    Controller.m或者

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *CellID = @"YourCellID";
        YourCell *cell = (YourCell *)[tableView dequeueReusableCellWithIdentifier:CellID];
    
        if (cell == nil) {
            cell = [[YourCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
        }
    
        cell.delegate = self;
    
        YourModel *model = self.yourDataArray[indexPath.row];
        cell.yourDataUsedToShownInUI = model.dataToShownInUI;
        if (model.downloading) {
            cell.status = YourCellStatusDownloading;
        } else if (model.completed) {
            cell.status = YourCellStatusCompleted;
        } else {
            cell.status = YourCellStatusNormal;
        }
    
        //other configs ...
    
        return cell;
    }
    
    - (void)didPressedButtonInYourCell:(id)sender {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
        YourModel *model = self.yourDataArray[indexPath.row];
        model.downloading = YES;
    
        //start downloading
        //...
        // in download completion handler, update your model status, and call
        //[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }