繁体   English   中英

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

[英]Can I save a file on the 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或Mail中)的按钮,并且用户想要打开文本文件,您的应用程序就会显示在列表中。

您还必须在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];

上面的方法将在NSString中为您提供文本文件的内容,称为content

那应该工作! 祝你好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM