下载并替换目录中的文件

时间:2016-02-09 15:33:28

标签: ios objective-c iphone

我正在尝试从URL下载文件,但问题是,当我打开下载的文件时,它会打开我之前下载的最后一个文件!我的意思是,如果我下载image1.png并打开它,然后尝试下载并替换image2.png,当我要打开上次下载的文件时,该文件仍为image1.png

这是我的代码:

- (void)downloadDataFromMac {

    [MBProgressHUD showHUDAddedTo:self.view animated:nil];

    NSString *replace = [absulutePath stringByReplacingOccurrencesOfString:@" " withString:@"%20" options:NSLiteralSearch range:NSMakeRange(0, [absulutePath length])];
    pathWithData = [NSString stringWithFormat:@"http://192.168.1.36:8888/?req=getimg&key=%@",replace];
    NSURL *URL = [NSURL URLWithString:pathWithData];


    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    NSProgress  *progress;
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {


        NSURL *documentsDirectoryURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]objectAtIndex:0];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];


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

        NSLog(@"File downloaded to: %@", filePath);

        //Hide HUD

            [MBProgressHUD hideHUDForView:self.view animated:YES];

            self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:filePath];

            [self.documentInteractionController setDelegate:self];

            [self.documentInteractionController presentPreviewAnimated:YES];

        }];


    [downloadTask resume];

}

任何帮助?,谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

//Saving images
-(BOOL) saveImage:(UIImage *) image filePath:(NSString *) filePath
{
    // Creating path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *fileFullPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:filePath];
    // Saving image.
    BOOL success =  [UIImageJPEGRepresentation(image, 1.0) writeToFile:fileFullPath atomically:YES];
    if (!success) {
        NSLog(LogPropertyError, @"Couldn't save image to disk %@",fileFullPath);
    }
    return success;
}