40

假设我正在使用此代码将图像保存到文档目录

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
    if let dirPath = paths[0] as? String {
        let readPath = dirPath.stringByAppendingPathComponent("Image.png")
        let image = UIImage(named: readPath)
        let writePath = dirPath.stringByAppendingPathComponent("Image2.png") 
        UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
    }
  }
}

然后我将如何检索它?请记住,与 iOS8 相比,确切的路径经常更改

4

5 回答 5

119

您在运行时找到用于写入图像的文档目录路径,为了读取它,您可以使用确切的逻辑:

斯威夫特 3 和斯威夫特 4.2

let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
let paths               = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath          = paths.first
{
   let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Image2.png")
   let image    = UIImage(contentsOfFile: imageURL.path)
   // Do whatever you want with the image
}

斯威夫特 2

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask    = NSSearchPathDomainMask.UserDomainMask
if let paths            = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
{
     if paths.count > 0
     {
         if let dirPath   = paths[0] as? String
         {
             let readPath = dirPath.stringByAppendingPathComponent("Image2.png")
             let image    = UIImage(contentsOfFile: readPath)
             // Do whatever you want with the image
         }
     }
}
于 2015-03-12T09:26:02.600 回答
13

作为扩展更好。

extension URL {
    static var documentsDirectory: URL {
        let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        return try! documentsDirectory.asURL()
    }

    static func urlInDocumentsDirectory(with filename: String) -> URL {
        return documentsDirectory.appendingPathComponent(filename)
    }
}

像这样使用:

let path = URL.urlInDocumentsDirectory(with: filename).path
let image = UIImage(contentsOfFile: path)
于 2017-03-24T18:18:59.497 回答
9

从文件夹或目录加载多个图像。- 斯威夫特 4

这是附加的图像,我们希望在下面给出的代码中实现。 在此处输入图像描述

这是从文档目录中的文件夹中查找多个图像的代码。我写了一种方法来做同样的事情。

在代码中,我们传递“文件夹名称”(即红色)并获取该目录的内容。作为回报,我们得到了图像名称数组。

    static func loadImagesFromAlbum(folderName:String) -> [String]{

    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
    let nsUserDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
    let paths               = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
    var theItems = [String]()
    if let dirPath          = paths.first
    {
        let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(folderName)

        do {
            theItems = try FileManager.default.contentsOfDirectory(atPath: imageURL.path)
            return theItems
        } catch let error as NSError {
            print(error.localizedDescription)
            return theItems
        }
    }
    return theItems
}

这是给定代码的结果。 在此处输入图像描述

希望能帮助到你。

谢谢

于 2018-02-28T12:36:58.067 回答
9

斯威夫特 2

如果你想在 Swift 2 中从你的文档目录中获取一个文件:

let path: String? = NSBundle.mainBundle().pathForResource("imageName", ofType: "png", inDirectory: "DirectoryName/Images")
let imageFromPath = UIImage(contentsOfFile: path!)!
self.myImage.image = imageFromPath

希望对某人有所帮助

于 2016-01-04T16:13:06.757 回答
-1
// --------------------------------------------------------
// MARK:- Document Directory
// --------------------------------------------------------

///# Get Data from document directory #///

private func getDocumentData(){
    
    ///# Path #///
    
    let folderPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("MyZipFiles") /// * folder *///
    let filePath = URL(fileURLWithPath: folderPath).appendingPathComponent("\(self.id)/\(self.titleVideo)") ///* inside folder all files *///
    print(filePath)

    ///# Get JsonFile from Directory with alamofire #///
    
    let jsonFilePath = URL(fileURLWithPath: folderPath).appendingPathComponent("\(self.id)/\(self.titleVideo)/python.json") ///* inside filename *///
    if (try! jsonFilePath.checkResourceIsReachable()) {
        print("file exist")
        Alamofire.request(jsonFilePath, method: .get, parameters: nil).responseData { (response) in
            guard let data = response.data else { return }
            do{
                let json = try SwiftyJSON.JSON(data: data)
                let results = json["images"]
                for arr in results.arrayValue{
                    self.arrImageData.append(Images(json: arr))
                }
                self._pickerCollectionView.reloadData()
                print(self.arrImageData)
            }catch{
                print(error.localizedDescription)
            }
        }

        ///# Back  Video #///
        let backVideoPath = URL(fileURLWithPath: folderPath).appendingPathComponent("\(self.id)/\(self.titleVideo)/background_video.mp4") ///* inside filename *///
        print(backVideoPath)

        
        ///# Output Video #///
        let outputPath = URL(fileURLWithPath: folderPath).appendingPathComponent("\(self.id)/\(self.titleVideo)/output.mp4")
        print(outputPath)

        ///# Get images string from documentdirectory #///
        
        do {
            let imagesData = try FileManager.default.contentsOfDirectory(atPath: filePath.path)  ///* Base Path to find Image *///
            
            ///# for loop to append path to find saved images and fill image array #///
            
        for imgStr in imagesData{
            if imgStr.hasPrefix("img"){
                imagesArr.append(imgStr)
                print(imagesArr)
                let document = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("MyZipFiles")
                print(document)
                
                let loadImage = document.appendingPathComponent("\(self.id)/\(self.titleVideo)")
                
                let imgUrl = loadImage.appendingPathComponent(imgStr, isDirectory: true)
                print(imgUrl.path)

                if let data = UIImage(named: imgStr)?.pngData() ,
                   !FileManager.default.fileExists(atPath: imgUrl.path){
                    do{
                        ///* write data to convert string images into url in document folder *///
                        
                        try data.write(to: imgUrl)
                        print("Image Add Successfully")
                        Log.debug(imgStr)
                    }
                    catch{
                        print("Image Not Added")
                    }
                }
                ///* append written url into array of images *///

                imgArr.append(imgUrl)
            }
        }
    }
        catch let err{
            print(err.localizedDescription)
        }
    }
}
于 2021-08-17T09:46:17.270 回答