用照片构建SQLite数据库

时间:2016-12-08 15:03:48

标签: ios swift database image sqlite

我的目标是在一个UICollectionView控制器中显示用户从DetailViewController收集的图像。我想使用SQLite数据库,但我不确定如何启动它,因为我已经建立并建立了我的大部分应用程序。下面是我的DetailViewController(图像是收集和显示的位置),ImageStore.swift(当前存储图像的位置)和UICollectionView控制器。

ImageStore.swift:

import re
sentence = "try to be nice; underastand people. start fresh."
sentence = re.sub(r';[^.]+', '', sentence)
print(sentence)
# => try to be nice. start fresh.

DetailViewController:

class ImageStore: NSObject {

 let cache = NSCache()

 func setImage(image: UIImage, forKey key: String) {
  cache.setObject(image, forKey: key)

  let imageURL = imageURLForKey(key)

  if let data = UIImageJPEGRepresentation(image, 0.5) {
    data.writeToURL(imageURL, atomically: true)
  }
}
func imageForKey(key: String) -> UIImage? {
 if let existingImage = cache.objectForKey(key) as? UIImage {
   return existingImage
}

let imageURL = imageURLForKey(key)
guard let imageFromDisk = UIImage(contentsOfFile: imageURL.path!) else {
    return nil
}

cache.setObject(imageFromDisk, forKey: key)
return imageFromDisk
}

func deleteImageForKey(key: String) {
 cache.removeObjectForKey(key)

 let imageURL = imageURLForKey(key)
do {
    try NSFileManager.defaultManager().removeItemAtURL(imageURL)
}
catch let deleteError {
    print("Error removing the image from disk: \(deleteError)")
  }
}

func imageURLForKey(key: String) -> NSURL {
 let documentsDirectories = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
 let documentDirectory = documentsDirectories.first!

 return documentDirectory.URLByAppendingPathComponent(key)
}

UICollectionView:

var imageStore: ImageStore!

@IBAction func takePicture(sender: UIBarButtonItem) {
 let imagePicker = UIImagePickerController()

  if UIImagePickerController.isSourceTypeAvailable(.Camera) {
    imagePicker.sourceType = .Camera
  } else {
    imagePicker.sourceType = .PhotoLibrary
   }
 imagePicker.delegate = self

 presentViewController(imagePicker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController,  didFinishPickingMediaWithInfo info: [String: AnyObject]) {

let image = info[UIImagePickerControllerOriginalImage] as! UIImage

imageStore.setImage(image, forKey: item.itemKey)

imageView.image = image

dismissViewControllerAnimated(true, completion: nil)

}

0 个答案:

没有答案