将文件传输到物理iOS设备

时间:2015-09-08 02:05:33

标签: ios xcode ipad

我已经设置了配置文件,以便在连接的物理设备上调试我的应用程序(通过Xcode)。

问题是此应用程序需要某些支持文件。使用Mac上的模拟器,我只需导航到模拟器目录下的应用程序的Documents目录,然后将文件放在那里。

有没有办法将这些相同的文件放到物理设备上?

1 个答案:

答案 0 :(得分:3)

将文件放在项目文件结构中。 因此,它们将被复制到您的App Bundle中,并可通过文档目录获取。

正确地将文件添加到iOS项目:

  1. 右键单击左侧文件列表顶部的项目图标。
  2. 选择Add files to <YourProjectName>
  3. 选择要包含的文件夹/文件,然后单击“添加”。
    • 不要忘记从给定列表中选择正确的target。请参阅屏幕截图。
  4. 如果您的资源不是单个文件而是目录结构,并且您希望复制所有目录树,请记住选择添加的文件夹:创建组
  5. 添加弹出窗口的文件在XCode 6.x中看起来如下所示: enter image description here

    构建目标时,打开捆绑包,您的目录结构将完全存在于内部。不仅如此,这些文件可以通过iOS SDK访问,如下所示。

    因此您可能需要将它们复制到应用程序中的文档/库目录,因为您可能希望在应用程序中访问它们。

    使用以下代码复制它们。

    // Check if the file has already been saved to the users phone, if not then copy it over
    BOOL success;
    NSString *fileName = @"test.jpg";
    NSString *LIBRARY_DIR_PATH = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *filePath = [LIBRARY_DIR_PATH stringByAppendingPathComponent:fileName];
    NSLog(@"%@",filePath);
    
    // Create a FileManager object, we will use this to check the status
    // of the file and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // Check if the file has already been created in the users filesystem
    success = [fileManager fileExistsAtPath:filePath];
    
    // If the file already exists then return without doing anything
    if(success) return;
    
    // Else,
    NSLog(@"FILE WASN'T THERE! SO GONNA COPY IT!");
    
    // then proceed to copy the file from the application to the users filesystem
    // Get the path to the files in the application package
    NSString *filePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
    
    // Copy the file from the package to the users filesystem
    [fileManager copyItemAtPath:filePathFromApp toPath:filePath error:nil];
    

    希望上面的代码示例对您来说很清楚。

    因此,无论何时您想在App中访问该文件,都可以通过获取该文件来获取对该文件的引用,如下所示:

        NSString *sqliteDB = [LIBRARY_DIR_PATH stringByAppendingPathComponent:fileName];
    

    注意:在任何情况下,如果您要求将文件复制到用户应用安装位置内的Documents目录,请将LIBRARY_DIR_PATH替换为以下内容:

    NSString *DOCUMENTS_DIR_PATH = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    

    希望这个答案对你有所帮助!

    干杯!

相关问题