iOS - 仅下载修改后的文件(NSURL 和 NSData)

2023-12-05

我正在从服务器下载一堆图像文件,并且我想确保仅在更新时才下载它们。 目前,此方法可以很好地下载图像。但是,我不想在用户每次登录应用程序时浪费时间或精力重新下载图像。相反,我只想下载 A) 不存在 B) 服务器上比设备上更新的任何文件

这是我下载图像的方式: *图像 URL 与其关联的视频一起保存在 Core Data 中。 url是使用我构建的简单转换方法生成的(生成缩略图URL)

-(void)saveThumbnails{
    NSManagedObjectContext *context = [self managedObjectContextThumbnails];
    NSError *error;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Videos" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    NSLog(@"Videos: %i",fetchedObjects.count);
    if (fetchedObjects.count!=0) {
        for(Videos *currentVideo in fetchedObjects){
            // Get an image from the URL below
            NSURL *thumbnailURL = [self generateThumbnailURL:[currentVideo.videoID intValue]];

            UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:thumbnailURL]];

            // Let's save the file into Document folder.
            // You can also change this to your desktop for testing. (e.g. /Users/kiichi/Desktop/)
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//Find Application's Document Directory
            NSString *documentsDirectory = [paths objectAtIndex:0];
            NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"DownloadedThumbnails"];
            //        NSString *dataPath = @"/Users/macminidemo/Desktop/gt";//DEBUG SAVING IMAGE BY SAVING TO DESKTOP FOLDER

            //Check if Sub-directory exists, if not, try to create it
            if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
                NSError* error;
                if([[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]){
                    NSLog(@"New Folder Created!");
                }
                else
                {
                    NSLog(@"[%@] ERROR: attempting to write create new directory", [self class]);
                    NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
                }
            }
            NSArray *splitFilename = [[self generateThumbnailFilename:[currentVideo.videoID intValue]] componentsSeparatedByString:@"."];//Break Filename Extension Off (not always PNGs)
            NSString *subString = [splitFilename objectAtIndex:0];
            NSString *formattedFilename = [NSString stringWithFormat:@"%@~ipad.png",subString];
            NSString *localFilePath = [dataPath stringByAppendingPathComponent:formattedFilename];
            NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
            [imageData writeToFile:localFilePath atomically:YES];
            NSLog(@"Image: %@ Saved!",formattedFilename);
        }
    }
}

我最终使用此方法来检测文件的修改日期: *发现于HERE

-(bool)isThumbnailModified:(NSURL *)thumbnailURL forFile:(NSString *)thumbnailFilePath{
    // create a HTTP request to get the file information from the web server
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:thumbnailURL];
    [request setHTTPMethod:@"HEAD"];

    NSHTTPURLResponse* response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

    // get the last modified info from the HTTP header
    NSString* httpLastModified = nil;
    if ([response respondsToSelector:@selector(allHeaderFields)])
    {
        httpLastModified = [[response allHeaderFields]
                            objectForKey:@"Last-Modified"];
    }

    // setup a date formatter to query the server file's modified date
    // don't ask me about this part of the code ... it works, that's all I know :)
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";
    df.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];

    // get the file attributes to retrieve the local file's modified date
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary* fileAttributes = [fileManager attributesOfItemAtPath:thumbnailFilePath error:nil];

    // test if the server file's date is later than the local file's date
    NSDate* serverFileDate = [df dateFromString:httpLastModified];
    NSDate* localFileDate = [fileAttributes fileModificationDate];

    NSLog(@"Local File Date: %@ Server File Date: %@",localFileDate,serverFileDate);
    //If file doesn't exist, download it
    if(localFileDate==nil){
        return YES;
    }
    return ([localFileDate laterDate:serverFileDate] == serverFileDate);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS - 仅下载修改后的文件(NSURL 和 NSData) 的相关文章

  • Swift UIToolBar 追加 UIBarButtonItem 项目

    我的语法不正确 有人知道这里缺少什么吗 我正在使用 Xcode 6 beta 3 并且尝试将工具栏项动态添加到 viewDidLoad 中的 手动添加的 工具栏 有两个问题 首先 我无法将工具栏中的项目附加到数组中 其次 虽然编译器允许我调
  • 在 Grand Central Dispatch 中使用dispatch_sync

    任何人都可以用非常清晰的用例解释其目的是什么dispatch sync in GCD是为了 我不明白在哪里以及为什么我必须使用它 Thanks 当您想要执行一个块并等待结果时可以使用它 其中一个示例是使用调度队列而不是锁进行同步的模式 例如
  • 如何检查dispatch_async块是否已完成运行

    所以基本上我需要能够在块完成运行后运行 segue 我有一个块可以执行一些 JSON 操作 我需要知道它何时完成运行 我有一个队列 我称之为 json queue jsonQueue dispatch queue create com ja
  • iOS 上服务器发送事件的 webkit 的推荐替代方案 [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我想在我的本机 iOS 应用程序中接收服务器发送的事件 但我不使用 webkit Safari 根据我
  • 跨平台 IAP

    我已在 iOS 和 Android 中集成了应用内购买 自动续订订阅 两者都工作正常 我对使用跨平台验证 IAP 有一定的疑问 例如 当多个用户登录一个应用程序时 某一特定应用程序的订阅如何运作 例如 如果用户 A 有标准套餐并且从应用程序
  • 针对架构 armv7 的 iOS 链接器错误的 Google 转化跟踪

    我正在尝试将 iOS 版 Google 转化跟踪功能添加到我的 iPhone 应用程序中 该应用程序的基础 SDK 是 iOS6 该应用程序的有效架构是armv7 armv7s 该应用程序的 iOS 部署目标是 4 3 我正在使用最新的 x
  • iOS 15 中表视图标题上方的额外填充

    如何更改上面的额外填充UITableViewiOS 15 中开始出现的节标题 从 iOS 15 开始 UITableView包含一个名为的新属性sectionHeaderTopPadding https developer apple co
  • Sierra 更新后无法针对 iOS 10 进行编译

    我有一个今年八月生成的证书和配置文件 它们在 Apple 开发者门户中均有效 未过期 当我打开以 8 3 为目标的项目时 出现以下错误 No certificate matching iPhone Developer My Name ABC
  • 在 iPad 上运行时,不会触发 Mobile Safari 中即将发生的选项卡切换的 Pagehide 事件

    众所周知 Mobile Safari 在以下情况下会暂停网页上的 Javascript 执行 您切换到不同的浏览器选项卡 切换到不同的 iOS 应用程序 例如 当您接到来电时 手机应用程序 您可以订阅窗口 页面隐藏 and 页面展示 事件来
  • 检测 SFSafariViewController 中的 URL 更改

    我有一个 SFSafariViewController 当用户点击我的应用程序中的链接时 它会打开 我需要检测 URL 何时更改 这样当它更改时 应用程序会显示警报 我们如何检测 SFSafariViewController 中的 URL
  • 使用 NSPredicate 来检测 NOT CONTAINS

    我放弃 我已经尝试了我能想象到的所有组合来检查一个字符串是否包含另一个字符串 这是描述我想要做的事情的直观语法示例 NSPredicate pPredicate NSPredicate predicateWithFormat NOT K C
  • 什么是 iBeacon 蓝牙配置文件

    我想使用一些低功耗蓝牙开发套件创建自己的 iBeacon Apple 尚未发布 iBeacon 规范 但是 一些硬件开发人员已根据 AirLocate 示例代码对 iBeacon 进行了逆向工程 并开始销售 iBeacon 开发套件 那么
  • 按钮图像未显示在 UItextfield 的 rightView 中

    我创建了一个按钮图像 并使用 Sa wift 将其放置在 UITextField 密码 的 rightView 上 我想在密码字段中创建切换按钮隐藏 显示安全文本 右视图中显示的图像 Code func passwordToggleButt
  • 加快 SpriteSheet 的 UIImage 创建速度

    我不确定我的标题是否正确 但我不确定我的问题到底在哪里 我需要从 spritesheet 加载 UIImage 数组 然后将其用作 UIImageView 中的动画 spritesheet是用TexturePacker生成的 它生成巨大的图
  • 在 Interface Builder 中启用/禁用 NSLayoutConstraints

    NSLayoutConstraint in iOS 8 0 has a BOOL属性称为active这使得动态禁用 启用所述布局约束变得容易 要为视图控制器创建第二个布局集 然后我可以以编程方式启用 禁用它 通过IBOutletCollec
  • Android 和 iOS 中的应用程序文件大小差异

    通过使用两个应用程序分发服务 Android 市场和 Apple 应用程序商店 我发现了一个谜团 Apple 应用程序的文件大小通常大于 Android 应用程序 我似乎找不到任何对这些差异的解释 而且这似乎是一个未触及的主题 我尝试过分配
  • 从方案加载 url 第一次未处理 - appdelegate 与 viewcontroller

    我的应用程序已成功打开并将参数 从 URL 方案 即 myApp sometextToPrint 设置为AppDelegate类 但每当我想处理它们时 当从该 URL 打开应用程序时 它就会在第一次失败 我在前台检查器中有一个应用程序 它调
  • NSPredicate predicateWithFormat 传入属性名称

    关于 NSPredicate 的简单问题 我正在尝试使用 传入 值构建我的谓词 如下所示 NSPredicate currentPredicate NSPredicate predicateWithFormat key changesDic
  • 无效的 Swift 支持 - 文件位置不正确

    我一直在尝试将新版本上传到 iTunes Connect 来更新应用程序 我第一次使用 xCode 6 但收到了一封来自 Apple 的电子邮件 内容如下 亲爱的开发者 我们发现您最近交付的 应用程序 存在一个或多个问题 要处理您的交货 必
  • 将蒙版图像作为 PNG 文件写入磁盘

    基本上 我从网络服务器下载图像 然后将它们缓存到磁盘上 但在这样做之前 我想屏蔽它们 我正在使用每个人似乎都指出的屏蔽代码 可以在这里找到 http iosdevelopertips com cocoa how to mask an ima

随机推荐