我可以在iPhone上保存文件吗?



我有一个正在移植到iPhone的Android应用程序,一个重要的功能需要打开一个简单的文本文件,用户下载。 在Android上,通常的方法是用户将文件作为电子邮件附件获取,但是用户可以将文件下载到他们的iPhone以便我的应用程序可以打开它的任何方式都可以。 有没有办法在iPhone上做到这一点?

我不太确定您如何处理文本文件,但是当用户选择从应用程序中的邮件应用程序打开附件时,以下方法可以从附加的电子邮件中检索文本文件。

首先,您需要将应用注册为能够打开文本文件。为此,请转到应用的 info.plist 文件并添加以下部分:

<key>CFBundleDocumentTypes</key>
  <array>
      <dict>
        <key>CFBundleTypeName</key>
        <string>Text Document</string>
        <key>CFBundleTypeRole</key>
        <string>Viewer</string>
        <key>LSHandlerRank</key>
        <string>Alternate</string>
        <key>LSItemContentTypes</key>
        <array>
            <string>public.text</string>
        </array>
    </dict>
</array>

这将告诉 iOS 您的应用程序可以打开文本文件。现在,只要有一个按钮显示"打开方式..."(例如,在 Safari 浏览器或邮件中)如果用户想要打开文本文件,您的 App 将显示在列表中。

您还必须处理在 AppDelegate 中打开文本文件:

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{    
if (url != nil && [url isFileURL]) {
    //Removes the un-needed part of the file path so that only the File Name is left
    NSString *newString = [[url absoluteString] substringWithRange:NSMakeRange(96, [[url absoluteString] length]-96)];
    //Send the FileName to the USer Defaults so your app can get the file name later
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:newString forKey:@"fileURLFromApp"];
    //Save the Defaults
    [[NSUserDefaults standardUserDefaults] synchronize];
    //Post a Notification so your app knows what method to fire
    [[NSNotificationCenter defaultCenter] postNotificationName:@"fileURLFromApp" object:nil];
} else {
}
return YES;
}

您必须在ViewController.m中注册该通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fileURLFromApp) name:@"fileURLFromApp" object:nil];

然后,您可以创建所需的方法并检索文件:

- (void) fileURLFromApp
{   
//Get stored File Path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *filePath = [defaults objectForKey:@"fileURLFromApp"];
NSString *finalFilePath = [documentsDirectory stringByAppendingPathComponent:filePath];
//Parse the data
//Remove "%20" from filePath
NSString *strippedContent = [finalFilePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//Get the data from the file
NSString* content = [NSString stringWithContentsOfFile:strippedContent encoding:NSUTF8StringEncoding error:NULL];

上述方法将为您提供名为 content 的 NSString 中的文本文件的内容

这应该有效!祝你好运!