如何使用writeToFile将文件保存在文件目录中?

时间:2015-09-29 06:12:15

标签: ios image swift writetofile

// directoryPath is a URL from another VC
@IBAction func saveButtonTapped(sender: AnyObject) {
            let directoryPath           =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
            let urlString : NSURL       = directoryPath.URLByAppendingPathComponent("Image1.png")
            print("Image path : \(urlString)")
            if !NSFileManager.defaultManager().fileExistsAtPath(directoryPath.absoluteString) {
                UIImageJPEGRepresentation(self.image, 1.0)!.writeToFile(urlString.absoluteString, atomically: true)
                displayImageAdded.text  = "Image Added Successfully"
            } else {
                displayImageAdded.text  = "Image Not Added"
                print("image \(image))")
            }
        }

我没有收到任何错误,但图片未保存在文档中。

8 个答案:

答案 0 :(得分:25)

问题在于您正在检查文件夹是否不存在但是您应该检查该文件是否存在。您的代码中的另一个问题是您需要使用url.path而不是url.absoluteString。您还使用“png”文件扩展名保存jpeg图像。你应该使用“jpg”。

编辑/更新:

Swift 4.2或更高版本

// get the documents directory url
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// choose a name for your image
let fileName = "image.jpg"
// create the destination file url to save your image
let fileURL = documentsDirectory.appendingPathComponent(fileName)
// get your UIImage jpeg data representation and check if the destination file url already exists
if let data = image.jpegData(compressionQuality:  1.0),
  !FileManager.default.fileExists(atPath: fileURL.path) {
    do {
        // writes the image data to disk
        try data.write(to: fileURL)
        print("file saved")
    } catch {
        print("error saving file:", error)
    }
}

答案 1 :(得分:24)

这是我对 Swift 3 的回答,结合了以上2个答案:

let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
// create a name for your image
let fileURL = documentsDirectoryURL.appendingPathComponent("Savedframe.png")


if !FileManager.default.fileExists(atPath: fileURL.path) {
    do {
        try UIImagePNGRepresentation(imageView.image!)!.write(to: fileURL)
            print("Image Added Successfully")
        } catch {
            print(error)
        }
    } else {
        print("Image Not Added")
}

答案 2 :(得分:1)

@IBAction func saveButtonTapped(sender: AnyObject) {
let directoryPath           =  try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)    
let urlString : NSURL       = directoryPath.URLByAppendingPathComponent("Image1.png")
    print("Image path : \(urlString)")
    if !NSFileManager.defaultManager().fileExistsAtPath(urlString.path!) {
        UIImageJPEGRepresentation(self.image, 1.0)!.writeToFile(urlString.path! , atomically: true)
        displayImageAdded.text  = "Image Added Successfully"
    } else {
        displayImageAdded.text  = "Image Not Added"
        print("image \(image))")
    }
}

答案 3 :(得分:1)

将图像放在NSData对象中;使用此类写入文件是轻而易举的,它会使文件大小变小。

顺便说一句,我推荐使用NSPurgeableData。保存图像后,您可以将对象标记为可清除,这将保留内存消耗。这可能是您的应用程序的问题,但可能与另一个您挤出的问题。

答案 4 :(得分:1)

迅速4.2中的扩展方法

<form>
    <p>
        <select asp-for="MovieGenre" asp-items="Model.Genres">
            <option value="">All</option>
        </select>
        Title: <input type="text" asp-for="SearchString" />
        <input type="submit" value="Filter" />
        <a asp-route-MovieGenre="" asp-route-SearchString="" class="btn btn-primary">ReSet</a>
    </p>
</form>

答案 5 :(得分:0)

在Swift 4.2和Xcode 10.1中

func saveImageInDocsDir() {

    let image: UIImage? = yourImage//Here set your image
    if !(image == nil) {
        // get the documents directory url
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0] // Get documents folder
        let dataPath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("ImagesFolder").absoluteString //Set folder name
        print(dataPath)
        //Check is folder available or not, if not create 
        if !FileManager.default.fileExists(atPath: dataPath) {
            try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: true, attributes: nil) //Create folder if not
        }

        // create the destination file url to save your image
        let fileURL = URL(fileURLWithPath:dataPath).appendingPathComponent("imageName.jpg")//Your image name
        print(fileURL)
        // get your UIImage jpeg data representation
        let data = UIImageJPEGRepresentation(image!, 1.0)//Set image quality here
        do {
            // writes the image data to disk
            try data?.write(to: fileURL, options: .atomic)
        } catch {
            print("error:", error)
        }
    }
}

答案 6 :(得分:0)

尽管答案是正确的,但我希望为此共享实用程序功能。您可以使用以下2种方法在“文档目录”中保存和映像,然后从“文档目录”中加载图像。在这里您可以找到Detailed Article

disease_df

答案 7 :(得分:0)

Swift 5.x 的答案

func saveImageToDocumentsDirectory() {
        let directoryPath =  try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let urlString : NSURL = directoryPath.appendingPathComponent("Image1.png") as NSURL
            print("Image path : \(urlString)")
        if !FileManager.default.fileExists(atPath: urlString.path!) {
            do {
                try self.image.jpegData(compressionQuality: 1.0)!.write(to: urlString as URL)
                print ("Image Added Successfully")
            } catch {
                print ("Image Not added")
            }
        }
    }

注意:图片 = 您声明的图片。