我想阅读 txt 文件并从其他应用获取文件路径(例如:电子邮件)
例如: 用户向我发送电子邮件,附件是txt文件。我想打开txt文件并从我的应用程序中读取它。
我参考以下链接: https://developer.apple.com/library/ios/qa/qa1587/_index.html
当我从电子邮件中单击txt文件(附件)时,我的应用程序将显示在“打开...”菜单中。当我选择使用我的应用程序打开txt文件时,应用程序将打开。
但是如何在App打开后阅读txt文件并获取文件路径?
答案 0 :(得分:0)
该文件将存储在app document目录的 Inbox 文件夹中,您可以像这样搜索文档目录:
NSString *searchFilename = @"hello.txt"; // name of the txt file you are searching for
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *inboxFolderPath = [documentsDirectory stringByAppendingPathComponent:@"Inbox"];
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath: inboxFolderPath];
NSString *documentsSubpath;
while (documentsSubpath = [direnum nextObject])
{
if (![documentsSubpath.lastPathComponent isEqual:searchFilename]) {
continue;
}
NSLog(@"found %@", documentsSubpath);
}
如果您不知道文件名,则通过将documentsSubpath.lastPathComponent添加到tableview上显示的数组来显示文件名列表
答案 1 :(得分:0)
您的解决方案似乎很好,尝试从另一个应用中打开AppDelegate中的launchOptions
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
。
应用程序是沙盒的,这意味着应用程序无法相互访问(共享同一组的应用程序的例外)。
您还想查看Apple iOS Application Extension Actions。
基本上,当您收到电子邮件时,长按附件会提示您一个操作对话框,您可以在其中共享,打印和执行各种操作。您可以使用Application Extensions在该列表中显示您自己的应用程序。
您可能需要查看整个 App Extension Programming Guide ,因为它非常完整和准确。也许你会发现伟大而意想不到的事情。
我建议您继续使用自己的解决方案。 didFinishLaunchingWithOptions:
用于了解应用何时启动以及 的启动方式(来自通知等)。
UIApplicationLaunchOptionsURLKey
包含一个NSURL对象,用于指定要打开的文件。
如果存在UIApplicationLaunchOptionsURLKey
密钥,则您的应用程序必须打开该密钥引用的文件并立即显示其内容
你应该这样做:
NSError *error;
NSURL *fileURL = launchOptions[UIApplicationLaunchOptionsURLKey];
NSString *myText = [NSString stringWithContentsOfURL:fileURL
encoding:NSUTF8StringEncoding
error:&error];
我找到了所有内容here。