iPhone - 检查文件是否需要更新/更新

not*_*uer 3 iphone download nsurl

我正在尝试创建一个简单的应用程序来检查iPhone上的.txt文件是否需要更新.现在我正在检查上次修改的html标题,我想将其与我iPhone中的文件进行比较.如果网站的日期晚于iPhone上的文件,则iPhone会下载并替换该文件.

我正在使用NSURL并且下载文件非常困难.

提前致谢

dar*_*s0n 6

ASIHTTPRequest是一个库,它将HTTP请求和一堆直观检查(如代理身份验证,缓存等)封装在一个整齐的类中,这是一个扩展NSURLRequest.我建议使用此功能,您可以从此处找到的可能选项中选择一个缓存策略.它看起来像你想要的ASIAskServerIfModifiedCachePolicy,它总是询问服务器是否有更新的版本,只有更新版本才下载(它检查Last-Modified:以及其他标题).您还可以组合此缓存策略,ASIFallbackToCacheIfLoadFailsCachePolicy以便在联系服务器失败时,仍将使用上次存储的版本.

示例代码:

#import "ASIHTTPRequest.h"
#import "ASIDownloadCache.h"

/* doing the actual check. replace your existing code with this. */
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:myTxtFileURL];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request setCachePolicy:ASIAskServerIfModifiedCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy];
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[request startSynchronous];
NSString *latestText = [request responseString];
[request release];
Run Code Online (Sandbox Code Playgroud)

请注意,我只使用[request startSynchronous]它,因为它很容易粘贴到示例代码中.你应该使用:

  1. [request setDelegate:self]然后ASIHTTPRequestDelegate在当前类中的某个地方实现协议来处理requestFinished:requestFailed:,或
  2. 一个块,您可以设置

    [request setCompletionBlock:^
    {
        /* code to run after the download finishes */
    }];
    [request setFailedBlock:^
    {
        /* code to run if the download failed */
    }];
    
    Run Code Online (Sandbox Code Playgroud)

这些都需要在之前完成[request startSynchronous],然后你需要startSynchronous改为startAsynchronous.请查看链接以获取有关" 如何使用它 "选项卡的更多文档.

编辑:你说你想比较文件本身.我不明白你想要什么,但如果你想将旧文件中的内容与新文件中的内容进行比较,那么你需要先获取旧文件文本的副本.去做这个:

ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:myTxtFileURL];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request setCachePolicy:ASIAskServerIfModifiedCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy];
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
NSStringEncoding encoding;
NSError *error = nil;
NSString *oldText =
[NSString stringWithContentsOfFile:[[ASIDownloadCache sharedCache] pathToCachedResponseDataForRequest:request]
                      usedEncoding:encoding
                             error:&error];
[request startSynchronous];
NSString *newText = [request responseString];
[request release];

/* now compare the NSString oldText to newText however you like. */
Run Code Online (Sandbox Code Playgroud)

学习成为优秀程序员的一部分是能够使用和探索可用的文档和资源.我建议您阅读我已链接到的文档,在iOS上阅读Apple的文档,或者在Google搜索下一个问题.Apple文档中有关比较字符串的部分在这里.