2016-12-09 80 views
0

在我的應用程序中,用戶從相機膠捲選擇圖像,並將其保存在文檔目錄中。然後圖像顯示在他們選擇圖像的ViewController上。我想要將圖像附加到UICollectionView。如何訪問圖像/從documentDirectory追加圖像?請參閱下面的代碼。讓我知道你是否需要我的項目的其他部分。訪問DocumentDirectory中的圖像iOS和UICollectionView

DetailViewController(當我最初顯示照片):

class DetailViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate { 

... 

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) 
} 

override func viewWillAppear(animated: Bool) { 

super.viewWillAppear(animated) 

let key = item.itemKey 

if let imageToDisplay = imageStore.imageForKey(key) { 
    imageView.image = imageToDisplay 
    } 
} 

ImageStore(我如何開始存儲照片):

import UIKit 

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:

import UIKit 

class PhotosViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { 

var collectionView: UICollectionView! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() 
    layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) 
    layout.itemSize = CGSize(width: 300, height: 490) 

    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) 
    collectionView.dataSource = self 
    collectionView.delegate = self 
    collectionView!.registerClass(FoodCell.self, forCellWithReuseIdentifier: "Cell") 
    collectionView.backgroundColor = UIColor.whiteColor() 
    self.view.addSubview(collectionView) 
} 

override func viewWillAppear(animated: Bool) { 
    super.viewWillAppear(animated) 
} 

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return images.count 
} 

var images: [UIImage] = [ 

] 

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! FoodCell 
    cell.textLabel.text = "" 
    cell.imageView.image = images[indexPath.row] 
    return cell 
} 

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
{ 
    print("User tapped on item \(indexPath.row)") 
} 


override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
    } 
} 

回答

0

你可以試試以這種方式保存並獲取您的圖像:

//Save image 
let img = UIImage() // Image from your picker 
let data = UIImagePNGRepresentation(img)! 
do { 
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String 
    try data.writeToFile("\(documentsPath)myImage", options: []) 

} catch { 
    print("Error") 
} 

// Get image 
do { 
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String 
    let readData = try NSData(contentsOfFile: "\(documentsPath)myImage", options: []) 
    let retreivedImage = UIImage(data: readData) 
} 
catch { 
    print("Error") 
} 

一樣https://stackoverflow.com/a/35685943/2894160

+0

我嘗試這樣做,但它沒有正確保存圖像。在我解散DetailViewController然後回到它之後,圖像不再顯示。 – Allie