gpt4 book ai didi

ios - 按日期对 PHAsset 获取结果进行分组的智能方法

转载 作者:行者123 更新时间:2023-12-03 17:43:00 25 4
gpt4 key购买 nike

与我正在做的事情相比,有没有更聪明/更合适的方法?
我创建了一个字典,并通过查看每个获取的 Assets 继续枚举和填充年/月/日。

        let assetFetchResult = PHAsset.fetchAssetsInAssetCollection(album, options: assetFetchOptions)
if assetFetchResult.count > 0 {
var fetchedAssets = [String:[String:[String:[PHAsset]]]]()
//[year[month[date:arrayOfPhotos]]]

assetFetchResult.enumerateObjectsUsingBlock({
object, index, stop in

let asset:PHAsset = object as! PHAsset
let dateComponents = NSCalendar.currentCalendar().components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: asset.creationDate)

//year group creation
if fetchedAssets["\(dateComponents.year)"] == nil {
fetchedAssets["\(dateComponents.year)"] = [String:[String:[PHAsset]]]()
}
//monthly group creation
if fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"] == nil {
fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"] = [String:[PHAsset]]()
}

//daily group creation
if fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"]!["\(dateComponents.day)"] == nil {
fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"]!["\(dateComponents.day)"] = [PHAsset]()
}

fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"]!["\(dateComponents.day)"]?.append(asset)
})
println(fetchedAssets)
return fetchedAssets
}

最佳答案

我建议使用 Dictionary grouping直接,更安全和自动管理,如下解释:https://developer.apple.com/documentation/swift/dictionary/3127163-init
这可以是您优化的代码:

let fetchedAssets = Dictionary(grouping: <#assets-array#>) { asset -> DateComponents in
return Calendar.current.dateComponents([.day, .year, .month], from: (asset.creationDate)!)
}
print( fetchedAssets )
您将在控制台中收到如下内容:
(lldb) po fetchedAssets.first
▿ Optional<(key: DateComponents, value: Array<Assets>)>
▿ some : 2 elements
▿ key : year: 2021 month: 5 day: 18 isLeapMonth: false
- year : 2021
- month : 5
- day : 18
- isLeapMonth : false
▿ value : 1 element
▿ 0 : Assets
- asset : <PHAsset: 0x7fcebcc43740> A86BC4A1-63E3-41EB-897D-695A395531D6/L0/001 mediaType=1/4, sourceType=1, (2112x1590), creationDate=2021-05-18 11:19:23 +0000, location=0, hidden=0, favorite=0, adjusted=0

(lldb)

关于ios - 按日期对 PHAsset 获取结果进行分组的智能方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31716088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com