【问题标题】:write url contents into a string using stringWithContentsOfURL cache使用 stringWithContentsOfURL 缓存将 url 内容写入字符串
【发布时间】:2011-10-26 14:02:07
【问题描述】:

我的代码正在从我的 Web 服务器上的 xml 文件写入 url 的内容,并将内容存储在字符串中,然后将其写入文档目录中的本地文件。当我第一次加载它时一切都很好,之后即使我再次运行这个视图,它总是会得到已经缓存在设备上的内容,并且没有来自网络服务器的更新。

如何强制它每次都从服务器上的文件中读取内容?

NSString * path = @"http://my-domain-name.com/myGlobalFile.xml";
NSString * myStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:path] encoding:NSUTF8StringEncoding error:nil];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
localFilePath = [documentsDirectory stringByAppendingPathComponent:@"myLocalFile.xml"];
[myStr writeToFile:localFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

【问题讨论】:

  • 在你的程序中,你在 sn-p 之上做什么?您可能还想检查 writeToFile 可以返回的错误对象。

标签: iphone objective-c ios sdk


【解决方案1】:

您可以使用NSURLRequestNSURLConnection 下载字符串(这实际上是一种更好的处理方式——异步方式——您还可以反馈进度(http://stackoverflow.com/questions /2267950/how-to-make-an-progress-bar-for-an-nsurlconnection-when-downloading-a-file))。

NSURLRequest 让您可以更好地控制要使用的缓存策略。

您可以按如下方式设置您的NSURLRequest

NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://my-domain-name.com/myGlobalFile.xml"] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];

您可以将NSURLRequestReloadIgnoringLocalCacheData 替换为http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html 中的值(如果您想选择不同的策略,请向下滚动到“NSURLRequestCachePolicy”。)

有关如何完成此代码的完整文档(以及您需要实现的必要委托方法),请参阅以下优秀文档:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

它会告诉你整个过程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 2013-10-30
    相关资源
    最近更新 更多