iOS8无法在应用程序组共享容器位置下创建文件夹/文件

时间:2014-09-10 09:09:21

标签: ios ios8 ios-app-extension ios-app-group

我使用以下代码在共享下创建文件夹/文件 容器路径。这将有助于应用扩展程序和包含应用程序的扩展程序可以访问数据。

获取共享容器网址的代码:

+(NSURL*)getSharedContainerURLPath
{
    NSFileManager *fm = [NSFileManager defaultManager];

    NSString *appGroupName = APP_EXTENSION_GROUP_NAME; /* For example */

    NSURL *groupContainerURL = [fm containerURLForSecurityApplicationGroupIdentifier:appGroupName];

    return groupContainerURL;
}

创建目录的代码

+(void)createDirAtSharedContainerPath
{
    NSString *sharedContainerPathLocation = [[self getSharedContainerURLPath] absoluteString];    
    NSString *directoryToCreate = @"user_abc";
    //basically this is <shared_container_file_path>/user_abc
    NSString *dirPath = [sharedContainerPathLocation stringByAppendingPathComponent:directoryToCreate];

    BOOL isdir;
    NSError *error = nil;

    NSFileManager *mgr = [[NSFileManager alloc]init];

    if (![mgr fileExistsAtPath:dirPath isDirectory:&isdir]) { //create a dir only that does not exists
        if (![mgr createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error]) {
                NSLog(@"error while creating dir: %@", error.localizedDescription);                
        } else {
                NSLog(@"dir was created....");
        }
    }
}

以上代码没有引发任何错误,表示成功,但我无法在共享容器路径下找到该文件夹​​。任何可能被赞赏的想法

3 个答案:

答案 0 :(得分:31)

我只是通过更改以下代码使代码工作

NSString *sharedContainerPathLocation = [[self getSharedContainerURLPath] absoluteString];

NSString *sharedContainerPathLocation = [[self getSharedContainerURLPath] path];    

答案 1 :(得分:2)

对于Swift

func createProjectDirectoryPath(path:String) -> String
    {
        let containerURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.abc")
        let logsPath = containerURL!.URLByAppendingPathComponent(path)
        //print(logsPath.path);

        do {
            try NSFileManager.defaultManager().createDirectoryAtPath(logsPath.path!, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog("Unable to create directory \(error.debugDescription)")
        }
        return logsPath.path!
    }

使用

var strSavePath : String = self.createProjectDirectoryPath("Large")

注意:设置应用程序组后,上面的代码对创建文件夹非常有用。

答案 2 :(得分:0)

@Swift 5的@Hardik Thakkar代码 此功能在共享应用程序组容器中创建目录并返回其路径。

func createProjectDirectoryPath(path:String) -> String
{
    let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.Notifications.appGroupIdentifier)
    let logsPath = containerURL!.appendingPathComponent(path)
    //print(logsPath.path);

    do {
        try FileManager.default.createDirectory(atPath: logsPath.path, withIntermediateDirectories: true, attributes: nil)
    } catch let error as NSError {
        print("Unable to create directory \(error.debugDescription)")
    }
    return logsPath.path
}