读取本地webarchive文件-occasionally-返回null WebResourceData
阿罗哈,读取本地webarchive文件-occasionally-返回null WebResourceData
我遇到一个问题,在IOS 6.1.3读取其中的webarchive文件 - 偶尔 - 在WebResourceData返回空。
这些都是已知的良好文件(在TextEdit中创建)存储在包中,通常读取正常。只是每隔一段时间,他们都不会。
在下面显示的简单测试中,我一遍又一遍地读取3个不同的文件,直到发现错误。对于iOS 6.1.3,我每次运行测试时都会遇到1到200次迭代之间的错误。我已经在各种设备和模拟器上运行了相同的结果。
// trying to find out why reading webarchives occasionally
// returns with empty WebResourceData from known good files.
//
- (BOOL) testMe {
NSMutableDictionary *plist = [[NSMutableDictionary alloc] initWithCapacity:100] ;
int iteration = 1;
BOOL ok = TRUE;
// keep going until we have an error
while (ok) {
NSArray *fileNames = @[@"file1",
@"file2",
@"file3" ];
// LOOP through the webArchives...
//
for (NSString *webarchiveName in fileNames) {
// get the webarchive template
//
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:webarchiveName withExtension:@"webarchive"];
//
NSData *plistData = [NSData dataWithContentsOfURL:fileURL];
NSString *error;
NSPropertyListFormat format;
//
plist = (NSMutableDictionary *)[NSPropertyListSerialization propertyListFromData:plistData
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&error];
// check to see if it loaded
//
//
if(!plist){
NSLog(@"ERROR: did not load %@", webarchiveName);
}else{
NSData *foundWebResourceData = [[plist objectForKey:@"WebMainResource"] objectForKey:@"WebResourceData"];
NSString *foundHTML = [NSString stringWithUTF8String:[foundWebResourceData bytes]];
if (foundHTML == NULL) {
NSLog(@" %@ descr = %@", webarchiveName, foundHTML);
[errorOutlet setText:[NSString stringWithFormat:@"%@ returned with no content (null) in WebResourceData", webarchiveName]];
ok = FALSE;
}
} //---- end of if plist exists
} // loop through all 3 files
[countOutlet setText:[NSString stringWithFormat:@"%d", iteration]];
++ iteration;
} // keep looping until error
return ok;
} // end of testMe
误差在两行显示出来:
NSData *foundWebResourceData = [[plist objectForKey:@"WebMainResource"] objectForKey:@"WebResourceData"];
NSString *foundHTML = [NSString stringWithUTF8String:[foundWebResourceData bytes]];
,但它并不一致。我通过创建一个新的xcode项目来隔离代码,除了显示迭代计数和重新测试按钮之外,这是唯一的活动。这些文件总是加载,并且始终拥有带WebResourceData键的WebMainResource。
一个可能的线索是,如果我将代码插入到ViewDidLoad中,它会运行更多的迭代,但仍然会找到空值。通过按钮操作调用[self testMe]会更快地发生错误...不知道为什么。
我有点茫然,希望它不是一个iOS错误,而是我只是缺少一些基本的东西。任何帮助,将不胜感激。
您可以尝试使用NSString的初始设计用于阅读的NSData:由daltonclaybrook
NSString *foundHTML = [[NSString alloc] initWithData:foundWebResourceData encoding:NSUTF8StringEncoding];
那确实有效!任何想法为什么另一种方式没有?从网络存档中获取数据的特定方式可以从这里和网络上的例子中找到。非常感谢,daltonclaybrook! – dale 2013-04-04 03:03:24
工作答案,请参阅下文。是啊!我会为他投票,但今天刚刚注册......但我确实将它作为答案进行了检查。再次感谢! – dale 2013-04-04 03:04:55