大家好,我有点沮丧,所以我希望能得到一些帮助。我的项目在 SwiftUI 中。我想使用图像选择器将图像保存到核心数据。我实现了让 ImagePicker 工作,但我努力转换 Image --> UIImage --> Data 然后保存它。项目运行没有错误,但它不保存图像。要知道问题在哪里,我实施了 3 个打印语句。image=给了一个值,UIImage(inputImage)=nil,Data当然是nil。
import SwiftUI
struct AddNewBean: View {
@Environment(\.presentationMode) var presentationMode
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Bean.entity(), sortDescriptors: []) var beans: FetchedResults<Bean>
@State var BeanRoaster: String = ""
@State var BeanName: String = ""
@State var BeanStyle: String = "Dark"
@State private var RoastDate = Date()
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter }
@State private var showImagePicker : Bool = false
@State private var image : Image?
@State private var inputImage: UIImage?
@State var imageAlt: Data = .init(count: 0)
let RStyles = ["Dark", "Medium", "Light"]
func loadImage() {
guard let inputImage = inputImage else { return }
image = Image(uiImage: inputImage)
}
var body: some View {
NavigationView {
VStack {
Form {
VStack {
image?.resizable().scaledToFit().aspectRatio(contentMode: .fit)
HStack {
Spacer()
Button("Open Camera"){
self.showImagePicker = true
}.padding(5)
.foregroundColor(Color.white)
.background(Color.accentColor)
.cornerRadius(10)
Spacer()
}.sheet(isPresented: self.$showImagePicker, onDismiss: loadImage){
PhotoCaptureView(showImagePicker: self.$showImagePicker, image: self.$image)
}
}
TextField("Röster", text: $BeanRoaster)
TextField("Name der Bohne", text: $BeanName)
Picker("Roestung", selection: $BeanStyle) {
ForEach(RStyles, id: \.self) {
Text($0)
}
}
DatePicker(selection: $RoastDate, in: ...Date(), displayedComponents: .date) {Text("Röstdatum")}
HStack {
Spacer()
if BeanRoaster != "" && BeanName != "" {
Button(action: {
//....
let pickedImage = self.inputImage?.jpegData(compressionQuality: 1.0)
print("image, inputimage, pickedImage")
print(self.image as Any) // prints: Optional(SwiftUI.Image(provider: SwiftUI.ImageProviderBox<__C.UIImage>))
print(self.inputImage as Any) // prints: nil
print(pickedImage as Any) // prints: nil
//.....
let bean = Bean(context: self.moc)
bean.id = UUID()
bean.roaster = "\(self.BeanRoaster)"
bean.name = "\(self.BeanName)"
bean.roastStyle = "\(self.BeanStyle)"
bean.roastDate = self.RoastDate
bean.active = true
bean.img = pickedImage
try? self.moc.save()
self.presentationMode.wrappedValue.dismiss()
}) {
Image(systemName: "tray")
.foregroundColor(.blue)
.font(.largeTitle)
.padding(.vertical)
}
Text("Save").foregroundColor(.blue)
Spacer()
} else {
HStack {
Spacer()
Text("Trage Bohnendaten ein!")
Spacer()
}
}
}
Section {
HStack {
Spacer()
Button(action: {self.presentationMode.wrappedValue.dismiss()}) {
Image(systemName: "")
.foregroundColor(.red)
.font(.largeTitle)
.padding(.vertical)
}
Text("Dismiss").foregroundColor(.red)
Spacer()
}
}
}.navigationBarTitle("New Bean")
}
}
}
}