我创建了一个应用程序,用于显示“照片”中的所有图像(而不是从照片中选择图像)。例如,可以访问“照片”中所有图像的Google相册,并且可以再次在其应用程序上显示。有人知道使用swift在我们的应用程序中重新显示“照片”中的所有图像吗?
答案 0 :(得分:0)
请尝试可能的方法。在xCode中测试:11.2.1
注意::在 Privacy - Photo Library Usage Description
中添加info.plist
,以允许从画廊访问照片
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"
}
}
}