收集两个精确日期之间的iPhone库照片

时间:2016-01-25 21:29:17

标签: ios swift frameworks

我正在尝试在swift中创建一个简单的控制器,这样我就可以在两个确切的日期之间收集图书馆的照片,例如2015年2月15日,2015年2月18日。 在我的搜索过程中,我读到了iOS的Photo Framework,我想知道是否有一种简单的方法可以根据上面提到的日期使用这样的框架查询照片库。我还想获得像地理位置这样的图像元数据。如果我能用相同的框架做到这一点,那就太棒了 谢谢你的回答

2 个答案:

答案 0 :(得分:2)

要在两个日期之间收集照片,首先需要创建代表日期范围开头和结尾的NSDate。这是NSDate扩展名(来自https://stackoverflow.com/a/24090354/2274694),可以根据字符串表示形式创建日期:

extension NSDate {
    convenience
    init(dateString:String) {
        let dateStringFormatter = NSDateFormatter()
        dateStringFormatter.dateFormat = "MM-dd-yyyy"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        let d = dateStringFormatter.dateFromString(dateString)!
        self.init(timeInterval:0, sinceDate:d)
    }
}

然后使用NSDatePHFetchResult的{​​{1}}创建谓词。

PHFetchOptions

更新了Swift 3:

import Photos

class ViewController: UIViewController {

    var images:[UIImage] = [] // <-- Array to hold the fetched images

    override func viewDidLoad() {
        fetchPhotosInRange(NSDate(dateString:"04-06-2015"), endDate: NSDate(dateString:"04-16-2015"))
    }

    func fetchPhotosInRange(startDate:NSDate, endDate:NSDate) {

        let imgManager = PHImageManager.defaultManager()

        let requestOptions = PHImageRequestOptions()
        requestOptions.synchronous = true
        requestOptions.networkAccessAllowed = true

        // Fetch the images between the start and end date
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "creationDate > %@ AND creationDate < %@", startDate, endDate)

        images = []

        if let fetchResult: PHFetchResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions) {
            // If the fetch result isn't empty,
            // proceed with the image request
            if fetchResult.count > 0 {
                // Perform the image request
                for var index = 0 ; index < fetchResult.count ; index++ {
                    let asset = fetchResult.objectAtIndex(index) as! PHAsset
                    imgManager.requestImageDataForAsset(asset, options: requestOptions, resultHandler: { (imageData: NSData?, dataUTI: String?, orientation: UIImageOrientation, info: [NSObject : AnyObject]?) -> Void in
                        if let imageData = imageData {
                            if let image = UIImage(data: imageData) {
                            // Add the returned image to your array
                                self.images += [image]
                            }
                        }
                        if self.images.count == fetchResult.count {
                            // Do something once all the images 
                            // have been fetched. (This if statement
                            // executes as long as all the images
                            // are found; but you should also handle
                            // the case where they're not all found.)
                        }
                    })
                }
            }
        }
    }
}

答案 1 :(得分:0)

首先,我要感谢'Lyndsey Scott'提供的如此出色的代码。真的很有帮助。可能会将错误返回给少数编译器,因为那些是最新的,并且代码需要稍作更新。因此,在这里,我给出了最新的更新代码,以使Lyndsey的代码对于 Swift 4.0 或更高版本的最新编译器而言不会出现错误。

extension NSDate {
convenience
init(dateString:String) {
    let dateStringFormatter = DateFormatter()
    dateStringFormatter.dateFormat = "MM-dd-yyyy"
    dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale?
    let d = dateStringFormatter.date(from: dateString)!
    self.init(timeInterval: 0, since: d)
}

}

然后使用NSDates为PHFetchResult的PHFetchOptions创建一个谓词。

import UIKit
import Photos

class ViewController: UIViewController {

var images:[UIImage] = [] // <-- Array to hold the fetched images

override func viewDidLoad() {
    super.viewDidLoad()
    fetchPhotosInRange(startDate: NSDate(dateString:"07-15-2018"), endDate: NSDate(dateString:"07-31-2018"))

}

func fetchPhotosInRange(startDate:NSDate, endDate:NSDate)  {

    let imgManager = PHImageManager.default()

    let requestOptions = PHImageRequestOptions()
    requestOptions.isSynchronous = true
    requestOptions.isNetworkAccessAllowed = true

    // Fetch the images between the start and end date
    let fetchOptions = PHFetchOptions()
    fetchOptions.predicate = NSPredicate(format: "creationDate > %@ AND creationDate < %@", startDate, endDate)

    images = []

    if let fetchResult: PHFetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions) {
        // If the fetch result isn't empty,
        // proceed with the image request
        if fetchResult.count > 0 {
            // Perform the image request
           for (index) in 0 ..< fetchResult.count {

           // for var index = 0 ; index < fetchResult.count ; index++ {
            let asset = fetchResult.object(at: index)
            // Request Image
            imgManager.requestImageData(for: asset, options: requestOptions, resultHandler: { (imageData, str, orientation, info) -> Void in

                    if let imageData = imageData {
                        if let image = UIImage(data: imageData) {
                            // Add the returned image to your array
                            self.images += [image]
                        }
                    }
                    if self.images.count == fetchResult.count {
                        // Do something once all the images
                        // have been fetched. (This if statement
                        // executes as long as all the images
                        // are found; but you should also handle
                        // the case where they're not all found.)
                    }
                })
            }
        }
    }
    print("images ==>\(images)")

}

快乐的编码。