标签: nsdocumentdirectory

如何在Swift中找到NSDocumentDirectory?

我正在尝试使用代码获取Documents文件夹的路径:

var documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory:0,NSSearchPathDomainMask:0,true)
Run Code Online (Sandbox Code Playgroud)

但Xcode给出了错误: Cannot convert expression's type 'AnyObject[]!' to type 'NSSearchPathDirectory'

我试图了解代码中的错误.

ios nsdocumentdirectory swift

159
推荐指数
8
解决办法
12万
查看次数

什么是文件目录(NSDocumentDirectory)?

有人可以向我解释iOS应用程序上的文档目录以及何时使用它?

以下是我目前的看法:

对我来说,它似乎是一个中央文件夹,用户可以存储该应用程序所需的任何文件.

这与Core Data存储数据的位置不同?

似乎每个应用程序都有自己的文档目录.

我可以自由创建文件目录的子目录,如文件目录/图像,或文件目录/视频?

ios nsdocumentdirectory

121
推荐指数
6
解决办法
13万
查看次数

从文档目录中删除指定的文件

我想从我的app文档目录中删除一个图像.我写的删除图片的代码是:

 -(void)removeImage:(NSString *)fileName
{
    fileManager = [NSFileManager defaultManager];
    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentsPath = [paths objectAtIndex:0];
    filePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", fileName]];
    [fileManager removeItemAtPath:filePath error:NULL];
    UIAlertView *removeSuccessFulAlert=[[UIAlertView alloc]initWithTitle:@"Congratulation:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
    [removeSuccessFulAlert show];
}
Run Code Online (Sandbox Code Playgroud)

它的工作部分.此代码从目录中删除文件,但是当我检查目录中的内容时,它仍然在那里显示图像名称.我想从目录中完全删除该文件.我应该在代码中更改什么来做同样的事情?谢谢

xcode objective-c ios nsdocumentdirectory

110
推荐指数
5
解决办法
11万
查看次数

如何使用Swift代码创建目录(NSFileManager)

我在转换Objective-C代码为Swift创建目录时遇到了一些麻烦.

Objective-C的:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
Run Code Online (Sandbox Code Playgroud)

objective-c nsfilemanager ios nsdocumentdirectory swift

43
推荐指数
3
解决办法
4万
查看次数

从文档目录中的目录中删除文件?

我创建了一个Temp目录来存储一些文件:

//MARK: -create save delete from directory
func createTempDirectoryToStoreFile(){
    var error: NSError?
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentsDirectory: AnyObject = paths[0]
    tempPath = documentsDirectory.stringByAppendingPathComponent("Temp")

    if (!NSFileManager.defaultManager().fileExistsAtPath(tempPath!)) {

        NSFileManager.defaultManager() .createDirectoryAtPath(tempPath!, withIntermediateDirectories: false, attributes: nil, error: &error)
   }
}
Run Code Online (Sandbox Code Playgroud)

没关系,现在我要删除目录中的所有文件......我试过如下:

func clearAllFilesFromTempDirectory(){

    var error: NSErrorPointer = nil
    let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
    var tempDirPath = dirPath.stringByAppendingPathComponent("Temp")
    var directoryContents: NSArray = fileManager.contentsOfDirectoryAtPath(tempDirPath, error: error)!

    if error == nil {
        for path in directoryContents {
            let fullPath = dirPath.stringByAppendingPathComponent(path …
Run Code Online (Sandbox Code Playgroud)

nsfilemanager ios nsdocumentdirectory swift

41
推荐指数
5
解决办法
4万
查看次数

如果目录不存在,是否有更安全的方法来创建目录?

如果目录不存在,我发现了这种创建目录的方法.但它看起来有点不稳定,我担心这可能会在1000次尝试中出现错误.

if(![[NSFileManager defaultManager] fileExistsAtPath:bundlePath]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:bundlePath withIntermediateDirectories:YES attributes:nil error:NULL];
}
Run Code Online (Sandbox Code Playgroud)

只有这个笨拙的方法fileExistsAtPath也可以查找文件,而不仅仅是目录.但对我来说,危险的是:如果这出错怎么办?我该怎么办?保证创建目录的最佳做法是什么,只有在目录不存在时才创建?

我知道文件系统操作永远不会安全.设备可能会在它开始从A到B的位置时突然耗尽电池电量.或者它会偶然发现一个坏位并挂了一秒钟.也许在一些很少的情况下,即使没有目录,它也会返回YES.简单地说:我不相信文件系统操作.

我怎样才能绝对安全?

filesystems objective-c nsfilemanager ios nsdocumentdirectory

38
推荐指数
4
解决办法
2万
查看次数

在NSDocumentDirectory上禁用数据备份时,CFURLSetResourcePropertyForKey失败

我正在尝试下载图像文件并存储NSDocumentDirectory.为此,我必须关闭iCloud和iTunes上的数据备份.以下是我的代码:

+(void)saveData:(NSData*)thedata:(NSString*)fileName
{
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
   NSFileManager *fileManager = [NSFileManager defaultManager];
   [fileManager createFileAtPath:localFilePath contents:thedata attributes:nil];
   //prevent files from backup on iCloud or iTune
   NSURL *fileURL = [NSURL URLWithString:localFilePath];
   [self addSkipBackupAttributeToItemAtURL:fileURL];
}
Run Code Online (Sandbox Code Playgroud)

对于我的addskipbackupattributetoitematurl:

+(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)fileURL
{
   if (![[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]])
   {
       NSLog(@"File %@ doesn't exist!",[fileURL path]);
       return NO;
   }
   NSString *currSysVer = [[UIDevice currentDevice] systemVersion];    
   if ([currSysVer isEqualToString:@"5.0.1"])
   {
       const char* filePath = [[fileURL path] …
Run Code Online (Sandbox Code Playgroud)

ios nsdocumentdirectory

31
推荐指数
1
解决办法
8422
查看次数

将文件保存在swift 3的文档目录中?

我使用以下代码将文件保存在swift 3的文档目录中:

fileManager = FileManager.default
// let documentDirectory = fileManager?.urls(for: .documentDirectory, in: .userDomainMask).first as String
var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
path = path + name

let image = #imageLiteral(resourceName: "Notifications")
let imageData = UIImageJPEGRepresentation(image, 0.5)
let bool = fileManager?.createFile(atPath: path, contents: imageData, attributes: nil)

print("bool is \(bool)")
return true
Run Code Online (Sandbox Code Playgroud)

但正如您所看到的,我不是filemanager用来获取文档目录路径,因为filemanager只提供URL而不是字符串.

问题:

  • 如何从文件管理器中获取字符串?
  • 我的代码中是否有崩溃的可能性?

nsfilemanager ios nsdocumentdirectory swift

25
推荐指数
3
解决办法
5万
查看次数

将数据保存到Swift中的.plist文件

我试图在swift中将数据保存到plist文件,但是数据没有显示,因为它在读取plist时保存了.这是我正在使用的代码.

var documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
var path : NSString = documentsDirectory.stringByAppendingPathComponent("data.plist")
var data : NSMutableDictionary = NSMutableDictionary(contentsOfFile: path)
data.setObject(self.object, forKey: "key")
data.writeToFile(path, atomically: true)
Run Code Online (Sandbox Code Playgroud)

编辑:我听说最好的方法是写入文档目录,所以我的问题是如何写入该目录中的文件?

plist ios nsdocumentdirectory swift

23
推荐指数
3
解决办法
4万
查看次数

如何从本地路径加载图像ios swift(按路径)

在我的应用程序中,我将图像存储在本地存储中,我正在我的数据库中保存该图像的路径.如何从该路径加载图像?

这是我用来保存图像的代码:

 let myimage : UIImage = UIImage(data: data)!
            let fileManager = NSFileManager.defaultManager()
            let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
            let documentDirectory = urls[0] as NSURL


            print(documentDirectory)
            let currentDate = NSDate()

            let dateFormatter = NSDateFormatter()
            dateFormatter.dateStyle = .NoStyle
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let convertedDate = dateFormatter.stringFromDate(currentDate)
            let imageURL = documentDirectory.URLByAppendingPathComponent(convertedDate)
            imageUrlPath  = imageURL.absoluteString
            print(imageUrlPath)
            UIImageJPEGRepresentation(myimage,1.0)!.writeToFile(imageUrlPath, atomically: true)
Run Code Online (Sandbox Code Playgroud)

这是我的图像存储的路径

file:///var/mobile/Containers/Data/Application/B2A1EE50-D800-4BB0-B475-6C7F210C913C/Documents/2016-06-01%2021:49:32
Run Code Online (Sandbox Code Playgroud)

这是我试图检索图像,但它没有显示任何东西.

let image : String = person?.valueForKey("image_local_path") as! String
        print(person!.valueForKey("image_local_path")! as! String)
        cell.img_message_music.image = UIImage(contentsOfFile: image)
Run Code Online (Sandbox Code Playgroud)

image ios nsdocumentdirectory swift

19
推荐指数
4
解决办法
4万
查看次数