xcode UIActivityViewController - 保留从 URL 读取的附加文件的文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17501662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 03:34:45  来源:igfitidea点击:

UIActivityViewController - preserve file name of attached files from read from URL

iosxcodeemailpdfuiactivityviewcontroller

提问by Mrwolfy

Is there an equivalent code to this (code below) for iOS6 UIActivityViewController? The question is, can I share data via url and preserve the file name? As of now the only way I can figure out how to do it is to convert the PDF to NSData and add the data as an activityItem. Works fine, but I lose the name of the attached pdf.

iOS6 UIActivityViewController 是否有与此等效的代码(下面的代码)?问题是,我可以通过 url 共享数据并保留文件名吗?到目前为止,我能弄清楚如何做到这一点的唯一方法是将 PDF 转换为 NSData 并将数据添加为活动项。工作正常,但我丢失了所附 pdf 的名称。

[composer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:@"myPDF.pdf"];

回答by Ned

yes I think it is possible, try this

是的,我认为这是可能的,试试这个

NSString *str = [[NSBundle mainBundle] pathForResource:@"AppDistributionGuide" ofType:@"pdf"]; 
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[@"Test", [NSURL fileURLWithPath:str]] applicationActivities:nil];

回答by Vignesh Kumar

Please refer to the following way to achieve this. Preserve file name of attached files from read from URL:

请参考以下方法来实现。保留从 URL 读取的附加文件的文件名:

dispatch_async(dispatch_get_main_queue(), ^ {
    NSData *fileData;
    NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [documentDir stringByAppendingPathComponent:@"filename.pdf"];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.test.com/filename.pdf"]];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if (error) {
            NSLog(@"Download Error:%@",error.description);
        }
        if (data) {
            fileData = data;
            [data writeToFile:filePath atomically:YES];
            NSLog(@"File is saved to %@",filePath);
        }
    }];
    if(fileData && filePath) {
            UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[[NSURL fileURLWithPath:filePath]] applicationActivities:nil];
            [self presentViewController:activityViewController animated:YES completion:nil];
    }
});