我的 class 实现了UIDocumentInteractionControllerDelegate,并且具有以下属性:@property (nonatomic,retain) UIDocumentInteractionController * documentInteractionController;

if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"whatsapp://app"]]) {
    UIImage     *iconImage = [UIImage imageNamed:@"bg_iPhone_5.jpg"];
    NSString    *savePath  = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/whatsAppTmp.wai"];

    [UIImageJPEGRepresentation(iconImage, 1.0) writeToFile:savePath atomically:YES];
    _documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:savePath]];
    _documentInteractionController.UTI = @"net.whatsapp.image";
    _documentInteractionController.delegate = self;
    [_documentInteractionController presentOpenInMenuFromRect:CGRectMake(0, 0, 0, 0) inView:self.view animated: YES];
}
else {
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"WhatsApp not installed." message:@"Your device has no WhatsApp installed." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

嗨,我已经使用了这段代码,但是图像共享无法正常工作。 DocumentInteractionController启动带有whatsapp图标的屏幕,当我单击它时,我的应用程序崩溃。

最佳答案

这是使用正确方法来设置用于写出临时映像的URL的代码:

if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"whatsapp://app"]]) {
    NSError *error = nil;
    NSURL *documentURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:&error];
    if (!documentURL) {
        NSLog(@"Error getting doucment directory: %@", error);
    }

    NSURL *tempFile = [documentURL URLByAppendingPathComponent:@"whatsAppTmp.wai"];
    UIImage *iconImage = [UIImage imageNamed:@"bg_iPhone_5.jpg"];

    NSData *imageData = UIImageJPEGRepresentation(iconImage, 1.0) ;
    if (![imageData writeToURL:tempFile options:NSDataWritingAtomic error:&error]) {
        NSLog(@"Error writing File: %@", error);
    }

    self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:tempFile];
    self.documentInteractionController.UTI = @"net.whatsapp.image";
    self.documentInteractionController.delegate = self;
    [self.documentInteractionController presentOpenInMenuFromRect:CGRectMake(0, 0, 0, 0) inView:self.view animated: YES];
}
else {
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"WhatsApp not installed." message:@"Your device has no WhatsApp installed." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

07-27 21:50