簡體   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