UIActivityViewController и UIDocumentInteractionController не отображают параметры

Я новичок в UIActivityViewController и, возможно, мне не хватает базового понимания. То, что я пытаюсь сделать, это прикрепить файл csv, xml и vcard к контроллеру активности и показать параметры dropbox, google drive и т. д. Я загрузил и установил приложения Dropbox, Google Drive и т. д. на свой iPhone.

Теперь, когда я запускаю UIActivityViewController, все, что я вижу, это сообщение по умолчанию и приложение электронной почты в моем контроллере активности. Как я могу сделать так, чтобы другие приложения тоже отображались на них? Нужно ли устанавливать отдельные SDK для каждого приложения и каким-то образом включать их в свое приложение?

Это то, что я хотел бы видеть

введите здесь описание изображения

но это то, что я вижу вместо этого.

введите здесь описание изображения

Вот код, который я пробовал до сих пор

-(IBAction) dropBoxAction
{

    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask ,YES);
    NSString* documentsPath = [paths objectAtIndex:0];

    //CSV
    NSMutableString *fileNameStr = [NSMutableString stringWithFormat:@"test_CSV_Backup.csv"];
    NSString* csvDataFileStr = [documentsPath stringByAppendingPathComponent:fileNameStr];
    NSData *csvData = [NSData dataWithContentsOfFile:csvDataFileStr];

    //EXCEL
    NSMutableString *fileNameStr2 = [NSMutableString stringWithFormat:@"test_EXCEL_Backup.xml"];
    NSString* excelDataFileStr = [documentsPath stringByAppendingPathComponent:fileNameStr2];
    NSData *excelData = [NSData dataWithContentsOfFile:excelDataFileStr];

    //VCARD
    NSMutableString *fileNameStr3 = [NSMutableString stringWithFormat:@"test_VCARD_Backup.vcf"];
    NSString* vcardDataFileStr = [documentsPath stringByAppendingPathComponent:fileNameStr3];
    NSData *vcardData = [NSData dataWithContentsOfFile:vcardDataFileStr];


    //adding them all together
    NSMutableArray *sharingItems = [NSMutableArray new];
    [sharingItems addObject:csvData];
    [sharingItems addObject:excelData];
    [sharingItems addObject:vcardData];

    UIActivity *activity = [[UIActivity alloc] init];
    NSArray *applicationActivities = @[activity];

    UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:sharingItems applicationActivities:applicationActivities];
    [self presentViewController:activityController animated:YES completion:nil];


}

person Sam B    schedule 30.11.2013    source источник


Ответы (4)


Как сказал @rmaddy, вы должны использовать UIDocumentInteractionController для замены UIActivityViewController, вот так:

UIDocumentInteractionController *dc = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:fileNameStr]];
[dc presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
person shanegao    schedule 30.11.2013
comment
спасибо за помощь. Я застрял, это именно тот недостающий код, который мне нужен. Ваш ответ помечен. - person Sam B; 01.12.2013

Для всех, кто интересуется будущим, вот весь код в одном месте. Оцените это, если это поможет.

В вашем файле *.h добавьте это

@interface v1BackupComplete : UIViewController <UIDocumentInteractionControllerDelegate>
{

    UIDocumentInteractionController *docController;

}

В вашем файле *.m добавьте это

/************************
 * Dropbox ACTION
 ************************/
-(IBAction) dropBoxAction2
{
    NSLog(@"dropBoxAction2 ...");

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask ,YES);
    NSString* documentsPath = [paths objectAtIndex:0];
    NSMutableString *fileNameStr3 = [NSMutableString stringWithFormat:@"test_VCARD_Backup.vcf"];
    NSString* vcardDataFileStr = [documentsPath stringByAppendingPathComponent:fileNameStr3];


    NSURL *fileURL = [NSURL fileURLWithPath:vcardDataFileStr];
    docController = [self setupControllerWithURL:fileURL
                                   usingDelegate:self];

    bool didShow = [docController presentOpenInMenuFromRect:self.view.bounds inView:self.view animated:YES];

    NSLog(@"didShow %d ...", didShow);

    if (!didShow)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR"
                                                        message:@"Sorry. The appropriate apps are not found on this device."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles: nil];
        [alert show];
    }
}


#pragma mark - UIDocumentInteractionControllerDelegate
- (UIDocumentInteractionController *) setupControllerWithURL:(NSURL *)fileURL
                                               usingDelegate:(id <UIDocumentInteractionControllerDelegate>)         interactionDelegate {

    UIDocumentInteractionController *interactionController =
    [UIDocumentInteractionController interactionControllerWithURL:fileURL];
    interactionController.delegate = interactionDelegate;

    return interactionController;
}

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
    return self.view.frame;
}
person Sam B    schedule 30.11.2013

UIActivityViewController показывает только стандартные встроенные действия, а также любые пользовательские действия, которые вы передаете как applicationActivities.

За то, что вы делаете, вы не хотите UIActivityViewController. Вы хотите UIDocumentInteractionController. Если вы просто хотите отобразить существующие приложения, которые могут открыть файл, используйте один из методов presentOpenInMenuFrom....

Но обратите внимание, что это должно использоваться только для одного файла, а не для трех.

В этом контексте передача трех файлов не имеет смысла.

person rmaddy    schedule 30.11.2013

Я использовал ваш код здесь, чтобы открыть с помощью Dropbox, и только после того, как я использовал метод presentPreview (ниже). Это сработало для меня. PDF-файл был показан в качестве предварительного просмотра, а затем на кнопке предварительного просмотра нажмите (вверху справа), чтобы опция Dropbox («открыть в Dropbox») выполнила свою работу. Как это работает в почтовом приложении в предварительном просмотре вложения.

[interactionController presentPreviewAnimated:YES];

Когда я попытался открыть с помощью presentOpenInMenuFromRect, он вылетел при выборе «открыть в раскрывающемся списке».

person Chen Cohen    schedule 12.07.2017