gpt4 book ai didi

swift - 如何显示照片中的图像(ios中的原始照片库)

转载 作者:行者123 更新时间:2023-12-05 00:46:17 24 4
gpt4 key购买 nike

我创建了一个显示照片中所有图像的应用程序(不从照片中选择图像)。例如,谷歌照片可以访问照片中的所有图像,并且可以在其应用程序上再次显示。有谁知道使用 swift 在我们的应用程序上重新显示照片中的所有图像?

最佳答案

请尝试可能的方法。在 xCode 中测试:11.2.1

注意:info.plist 中添加 Privacy - Photo Library Usage Description 来获得访问照片的权限画廊

import SwiftUI
import Photos

struct ContentView: View {
@ObservedObject var photos = PhotosModel()
var body: some View {
List(photos.allPhotos, id: \.self) { photo in
Image(uiImage: photo)
.resizable()
.frame(width: 200, height: 200, alignment: .center)
.aspectRatio(1, contentMode: .fit)
}
.alert(isPresented: .constant(self.photos.errorString != "") ) {
Alert(title: Text("Error"), message: Text(self.photos.errorString ), dismissButton: Alert.Button.default(Text("OK")))
}
}
}

class PhotosModel: ObservableObject {

@Published var allPhotos = [UIImage]()
@Published var errorString : String = ""

init() {
PHPhotoLibrary.requestAuthorization { (status) in
switch status {
case .authorized:
self.errorString = ""
self.getAllPhotos()
case .denied, .restricted:
self.errorString = "Photo access permission denied"
case .notDetermined:
self.errorString = "Photo access permission not determined"
@unknown default:
fatalError()
}
}
}

fileprivate func getAllPhotos() {

let manager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = false
requestOptions.deliveryMode = .highQualityFormat
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

let results: PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
if results.count > 0 {
for i in 0..<results.count {
let asset = results.object(at: i)
let size = CGSize(width: 700, height: 700) //You can change size here
manager.requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: requestOptions) { (image, _) in
if let image = image {
self.allPhotos.append(image)
} else {
print("error asset to image")
}
}
}
} else {
self.errorString = "No photos to display"
}
}
}

关于swift - 如何显示照片中的图像(ios中的原始照片库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61461114/

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