【问题标题】:iphone writeToFile: problemiphone writeToFile:问题
【发布时间】:2011-09-20 22:50:46
【问题描述】:

有没有办法将我的 .xml 文件保存到 "/Users/student/Library/Application Support/iPhone/Simulator/User/Applications/..." 以外的其他目录p>

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"accUserNames.xml"];
 BOOL ok = [content writeToFile:appFile atomically:YES encoding:NSUnicodeStringEncoding error:nil];
if (!ok) {
    NSLog(@"Error writing file !");
}

我希望将我的 .xml 文件写入桌面,有什么想法吗?

【问题讨论】:

    标签: iphone xml xcode


    【解决方案1】:

    希望下面的代码有所帮助,

    NSString *documentsDirectory = @"/Users/student/Desktop/";
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"accUserNames.xml"];
    BOOL ok = [content writeToFile:appFile atomically:YES encoding:NSUnicodeStringEncoding error:nil];
    if (!ok) {
        NSLog(@"Error writing file !");
    }
    

    【讨论】:

    • 谢谢,如果我想上传到服务器怎么办?例如NSString *documentsDirectory = @"www.blablah.com" ?
    • 你的意思是你想上传文件到服务器?还是别的什么?
    • 这个链接可以帮助stackoverflow.com/questions/1266176/…
    【解决方案2】:

    在 iPhone 模拟器中,您应该能够成功使用 @"/Users/student/Desktop/accUserNames.xml" 作为写入路径。但是,您不能在 iOS 设备上执行此操作(您将被限制在应用程序的沙箱目录中 - 建议您写入 Documents 文件夹或其中的其他文件夹,具体取决于您存储的数据类型)。


    编辑:我想我理解你的问题。这部分代码:

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

    有效地找到“/Users/student/Library/Application Support/iPhone/Simulator/User/Applications/...”的路径(这是您想要保存东西的正常位置)。但是如果你只是想暂时保存到桌面,你应该使用appFile = @"/Users/student/Desktop/accUserNames.xml"

    注意:我不提倡将此作为长期解决方案,但如果您只是想暂时查看程序的输出,它可以正常工作。

    【讨论】:

    • 是的,我尝试使用 @"/Users/student/Desktop/accUserNames.xml" 但结果是 "/Users/student/Library/Application Support/iPhone/Simulator/User/Applications/* *用户/学生/桌面/accUserNames.xml**"
    • @Steve Jabs:更新了我的答案,因为我想我更了解你想要什么。
    • 是的,只是想测试一下输出是否可以放在其他目录中,如果可行,那么也许我可以将 xml 文件写入服务器,谢谢!
    【解决方案3】:

    如果您想将文件上传到服务器(在您的示例中为“www.blahblah.com”),那么使用写入文件方法不是正确的方法。这仅用于将数据写入本地文件系统(或网络共享,但不适用于 iPhone)。

    如果您想将数据传输到网络服务器,您需要在服务器上安装一些东西来侦听连接请求,然后它需要接受从您的应用传输的数据。您不能像写入文件系统那样只将文件写入“www.blahblah.com”

    【讨论】:

      【解决方案4】:

      可能不使用代码,但您可以尝试以下操作:打开“Automator”(在 Utilities 文件夹中)并选择“文件夹操作”。作为输入文件夹,您指定文档的目录(/Users/student/Library/Application Support/iPhone/Simulator/User/Applications/...),然后从“Files & Folders”中选择“Duplicate Finder Items” ”和“移动查找器项目”并选择桌面。点击“保存”,为其命名,然后将文档文件夹中的所有文件复制到桌面。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-18
        • 2011-03-08
        • 2011-10-28
        相关资源
        最近更新 更多