我运行代码,如下所示。当我得到文件(NSData)时,出现以下错误:
"BOM could not extract archive: Couldn't read PKZip signature"
发生了什么?有人遇到这个问题吗?我该怎么解决?
NSString *url = [res objectForKey:@"url"];
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]]; if (nil != data) {
//init a pass library
PKPassLibrary* passLib = [[PKPassLibrary alloc] init];
NSError *error;
//init a pass object with the data
PKPass *pass = [[PKPass alloc] initWithData:data error:&error];
if(error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil];
[alertView show];
}
//check if pass library contains this pass already
if([passLib containsPass:pass]) {
//pass already exists in library, show an error message
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Pass Exists" message:@"The pass you are trying to add to Passbook is already present." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
} else {
//present view controller to add the pass to the library
PKAddPassesViewController *vc = [[PKAddPassesViewController alloc] initWithPass:pass];
[vc setDelegate:(id)self];
[self presentViewController:vc animated:YES completion:nil];
}
}
假设您尝试使用来自connectionDidReceiveData方法的NSData对象,这是错误的。您应该累积NSData对象,直到connectionDidFinishLoading。
你应该这样做:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (self.passData != nil) {
[self.passData appendData:data];
}
else {
self.passData = [NSMutableData dataWithData:data];
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *error;
PKPass *pass = [[PKPass alloc] initWithData:self.passData error:&error];
//add pass
self.passData = nil;
}
问题出在行
//init a pass object with the data
PKPass *pass = [[PKPass alloc] initWithData:data error:&error];
下载的数据已损坏。
如果您能够通过电子邮件/Safari添加通行证,那么问题是由NSData对象引起的。
在我的例子中,pkpass文件base64字符串值是在我转换为NSData对象的设备上收到的。PKPass对象能够读取我的通行证。以下是我使用的代码:
// dictionary contains base64string values of the pkpass file.
for (NSString *key in [dictionary allKeys])
{
NSError *error;
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:[dictionary valueForKey:key] options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
PKPass *pass = [[PKPass alloc] initWithData:decodedData error:&error];
[arrPasses addObject:pass];
}
if ([arrPasses count] > 0)
{
PKAddPassesViewController *vc = [[PKAddPassesViewController alloc] initWithPasses:arrPasses];
[self presentViewController:vc animated:YES completion:nil];
}
else
{
NSLog(@"Passes not found");
}
希望这能有所帮助!!