前提
こちらのサイトを参考にUIImageを@AppStorageを用いてUserDefaultに保存する機能を作っています。
https://keicon.hatenablog.com/entry/2021/05/10/191718
実現したいこと
- UIImageをUserdefaultに保存したい
発生している問題・エラーメッセージ
以下のソースコードの指定の部分に次のようなエラーコードが出てきます。
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
どのようにすればbindImageがnilにならないか、工夫があれば教えていただけたら嬉しいです。
該当のソースコード
FirstViewからSettingViewにnavigation遷移をしています。
FirstView
1import SwiftUI 2import UIKit 3 4struct FirstView: View { 5 6 @AppStorage("IntegerKey") var day = "" 7 @AppStorage("launchedName") var bindName = "Name" 8 @AppStorage("launchedImage") var bindImage: Data? 9 10 var body: some View { 11 NavigationView{ 12 if let uiimage = UIImage(data: bindImage!) { //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value 13 Image(uiImage: uiimage) 14 } else { 15 Image("") 16 } 17 .toolbar{ 18 ToolbarItemGroup(placement: .navigationBarTrailing) { 19 NavigationLink(destination: SettingView(bindName: $bindName, bindImage: $bindImage)) { 20 Label("Setting", systemImage: "gearshape") 21 } 22 } 23 } 24 } 25} 26}
SettingView
1import SwiftUI 2 3struct SettingView: View { 4 @State private var name:String = "" 5 @State var onSwitch = false 6 @Binding var bindName: String 7 @Binding var bindImage: Data? 8 9 var body: some View { 10 if (self.name.isEmpty){ 11 Button(action: { 12 13 }) { 14 Text("confirm") 15 .font(.title2) 16 .padding(16) 17 .foregroundColor(Color.white) 18 .cornerRadius(10) 19 }.disabled(self.name.isEmpty) 20 } else { 21 Button(action: { 22 bindName = name 23 bindImage = profile_image.pngData() 24 UserDefaults.standard.set(self.bindName, forKey: "launchedName") 25 UserDefaults.standard.set(self.bindImage, forKey: "launchedImage") 26 self.onSwitch.toggle() 27 self.presentationMode.wrappedValue.dismiss() 28 }) { 29 Text("confirm") 30 } 31 } 32 } 33}
補足情報(FW/ツールのバージョンなど)
macOS バージョン12.3.1
2.6 GHz 6コアIntel Core i7
Xcodeバージョン13.3.1
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。