Swift将图像(屏幕截图)保存到nsuserdefaults

时间:2015-08-09 14:23:17

标签: swift uiimage save uiimagepickercontroller nsuserdefaults

我有一个程序,用户“创建”一个图像,然后程序截取屏幕截图。然后,我想将此屏幕截图保存到数据库,最好是nsuserdefaults,因为我稍后在表视图中访问它。关于如何处理这个问题的任何其他建议都非常受欢迎:)

代码就像这样

let screenshot = getScreenshot() // saves the screenshot
var imagePaths = [String]()
// get the array of previous screenshots
if let _ = NSUserDefaults.standardUserDefaults().objectForKey(theKey)
{
   imagePaths = NSUserDefaults.standardDefaults().objectForKey(theKey) as! [String]   
}
// then I want to get a path to the image something like
let imagePath = screenshot.getPath() // although this is not a valid method, this is basically what I want
// add the imagePath
imagePaths.append(imagePath)
// finally I save the image
NSUserDefaults.standardUserDefaults().setObject(imagePaths, forKey: theKey)

1 个答案:

答案 0 :(得分:1)

您可以在Documents中创建目录,并将屏幕截图保存为常用文件。可以从日期和时间生成文件名以获得唯一性。

func saveImage(imageData: NSData)
{
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy hh.mm.ss"
    let filename = "\(dateFormatter.stringFromDate(NSDate())).png"

    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
    let imagesDirectory = documentsDirectory.stringByAppendingPathComponent("Images")
    let filePath = imagesDirectory.stringByAppendingPathComponent(filename)

    if !NSFileManager.defaultManager().fileExistsAtPath(imagesDirectory)
    {
        var error: NSError?

        NSFileManager.defaultManager().createDirectoryAtPath(imagesDirectory, withIntermediateDirectories: false, attributes: nil, error: &error)

        if error != nil
        {
            println("\(error!.localizedDescription)")
            return
        }
    }

    imageData.writeToFile(filePath, atomically: true)
}

func getImagesPaths() -> [String]?
{
    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
    let imagesDirectory = documentsDirectory.stringByAppendingPathComponent("Images")

    if let filenames = NSFileManager.defaultManager().contentsOfDirectoryAtPath(imagesDirectory, error: nil)
    {
        let imagePaths = filenames.map{"\(imagesDirectory)/\($0)"}.filter(){$0.pathExtension == "png"}
        return imagePaths.count > 0 ? imagePaths : nil
    }
    return nil
}

要保存图片,只需使用saveImage(data)即可。要获取图片路径,请使用getImagesPaths()

如果您需要UIImage数组,可以按照以下方式获取:

var images : [UIImage] = [ ]
if let imagePaths = getImagesPaths()
{
    for path in imagePaths
    {
        if let image = UIImage(contentsOfFile: path)
        {
            images.append(image)
        }
    }
}