Iphone 读取本地webarchive文件-偶尔-返回空WebResourceData
阿罗哈 我在iOS 6.1.3读取webarchive文件时遇到了一个问题,其中-偶尔--WebResourceData返回空值 这些是已知的好文件(在TextEdit中创建)存储在捆绑包中,通常读取良好。只是偶尔,他们不会 在下面显示的一个简单测试中,我反复阅读了3个不同的文件,直到发现错误。对于iOS 6.1.3,每次运行测试时,我都会遇到1到200次迭代之间的错误。我在不同的设备和模拟器上运行了这个程序,得到了相同的结果Iphone 读取本地webarchive文件-偶尔-返回空WebResourceData,iphone,ios,plist,webarchive,Iphone,Ios,Plist,Webarchive,阿罗哈 我在iOS 6.1.3读取webarchive文件时遇到了一个问题,其中-偶尔--WebResourceData返回空值 这些是已知的好文件(在TextEdit中创建)存储在捆绑包中,通常读取良好。只是偶尔,他们不会 在下面显示的一个简单测试中,我反复阅读了3个不同的文件,直到发现错误。对于iOS 6.1.3,每次运行测试时,我都会遇到1到200次迭代之间的错误。我在不同的设备和模拟器上运行了这个程序,得到了相同的结果 // trying to find out why read
// 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键的WebMain资源
一个可能的线索是,如果我将代码插入ViewDidLoad,它将运行更多的迭代,但仍然会找到空值。从按钮操作调用[self-testMe]会更快地命中错误…不确定原因
我有点不知所措,希望这不是一个iOS错误,而是一些基本的东西,我只是错过了。任何帮助都将不胜感激。您可以尝试使用专为读取NSData而设计的NSString初始值设定项:
NSString *foundHTML = [[NSString alloc] initWithData:foundWebResourceData encoding:NSUTF8StringEncoding];
那确实有效!你知道为什么另一条路不行吗?这种从网络档案中获取数据的特殊方式可以从这里和网络上的示例中找到。非常感谢,道尔顿·克莱布鲁克!daltonclaybrook的工作答案,见下文。赞成!我会投票支持他的,但今天刚注册。。。不过,我确实核实了答案。再次感谢!