Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When I click widget, error occurs: NSInvalidArgumentException, nil error #18

Open
spencer0124 opened this issue May 7, 2023 · 1 comment

Comments

@spencer0124
Copy link

It works well, but when i click to widget to launch the app, it always crashes
Any idea how to solve error about NSInvalidArgumentException, nil error?

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
*** First throw call stack:
(0x1b7f04e38 0x1b108f8d8 0x1b80aa078 0x1b80b53ac 0x1b7f202b8 0x1b7f20158 0x100d9eae8 0x100d9efe8 0x103d679f0 0x103d489fc 0x100fb2164 0x1bae0cadc 0x1bb046798 0x1bb047338 0x1ba8cfb1c 0x1ba8cfe3c 0x1bae0c7b4 0x1bb046734 0x1bb0470e8 0x1bf51b460 0x1bf51cf88 0x1bf52b7f4 0x1bf52b444 0x1b7f956c8 0x1b7f7702c 0x1b7f7beb0 0x1f2171368 0x1ba471668 0x1ba4712cc 0x1007c2448 0x1d6874960)
libc++abi: terminating with uncaught exception of type NSException

  • thread List Widget #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
    frame #0: 0x00000001f5a1f674 libsystem_kernel.dylib__pthread_kill + 8 libsystem_kernel.dylib:
    -> 0x1f5a1f674 <+8>: b.lo 0x1f5a1f694 ; <+40>
    0x1f5a1f678 <+12>: pacibsp
    0x1f5a1f67c <+16>: stp x29, x30, [sp, #-0x10]!
    0x1f5a1f680 <+20>: mov x29, sp
    Target 0: (Runner) stopped.
    Lost connection to device.
@spencer0124
Copy link
Author

spencer0124 commented May 7, 2023

I think it is weird because lock screen widget and home widget (generating barcode) works well,
but whenever i click the widget to open the app directly, it always crashes.
below is my flutter code and swift code.

==== 1. flutter code ====
WidgetKit.setItem(
'widgetData',
jsonEncode(WidgetData(
'${passwordController.text}10')),
'group.flutterioswidget1');
WidgetKit.reloadAllTimelines();

==== 2. swift code ====
//
// skkupass_widget.swift
// skkupass widget
//
// Created by --- on 2023/04/22.
//

import WidgetKit
import SwiftUI
import Intents
import CoreImage

struct FlutterData: Decodable, Hashable {
let text: String
}

struct SimpleEntry: TimelineEntry {
let date: Date
var flutterData: FlutterData?
}

// 언제 갱신할 것인가?
struct Provider: TimelineProvider {

// data가 없을때 보여줄 예시 (dummy data)
func placeholder(in context: Context) -> SimpleEntry {
    SimpleEntry(date: Date(), flutterData: FlutterData(text: "개인용 바코드가 여기 생성됩니다"))
}

// 실제 관련 data
func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
    let entry = SimpleEntry(date: Date(), flutterData: FlutterData(text: "개인용 바코드가 여기 생성됩니다"))
    completion(entry)
}

// 실제로 timeline 관련된 부분
    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
    //var entries: [SimpleEntry] = []
        
    let sharedDefaults = UserDefaults.init(suiteName: "group.flutterioswidget1")
    var flutterData: FlutterData? = nil
        
    
    
        if(sharedDefaults != nil) {
                do {
                  let shared = sharedDefaults?.string(forKey: "widgetData")
                  if(shared != nil){
                    let decoder = JSONDecoder()
                    flutterData = try decoder.decode(FlutterData.self, from: shared!.data(using: .utf8)!)
                  }
                } catch {
                  print(error)
                }
            }
    
        
        let entryDate = Calendar.current.date(byAdding: .hour, value:24, to:Date())!
        let entry = SimpleEntry(date: entryDate, flutterData: flutterData)
        let timeline = Timeline(entries: [entry], policy: .never)
        completion(timeline)
}

}

func generateBarcode(from string: String) -> UIImage? {
// Convert the string to data
let data = string.data(using: .ascii)

    // Create a CIFilter for Code 128 barcode generation
    guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else { return nil }
    
    // Set the input message for the filter
    filter.setValue(data, forKey: "inputMessage")
    
    // Get the output image from the filter
    guard let outputImage = filter.outputImage else { return nil }
    
    // Create a UIImage from the output image
    let context = CIContext()
    guard let cgImage = context.createCGImage(outputImage, from: outputImage.extent) else { return nil }
    return UIImage(cgImage: cgImage)
}

struct skkupass_widget: Widget {
let kind: String = "skkupass_widget"

var body: some WidgetConfiguration {
    StaticConfiguration(kind: kind, provider: Provider()) { entry in
         skkupasswidgetView(entry: entry)
    }
    .supportedFamilies([.systemMedium, .accessoryCircular, .accessoryInline, .accessoryRectangular])
    .configurationDisplayName("스꾸패스 위젯")
    .description("학생증 바코드를 보여주며, 클릭시 앱을 실행합니다")
}

}

struct skkupasswidgetView: View {
var entry: Provider.Entry

@Environment(\.widgetFamily) var family


@ViewBuilder
var body: some View {
    
    
    
    switch family {
    case .accessoryCircular:
        ZStack {
                Circle()
                    .fill(Color.black)
                Image("skkuinvert")
                    .resizable()
                    .frame(width: 57, height: 57)
            }

    case .accessoryRectangular:
        ZStack {
            HStack {
                Text("SKKU PASS")
                    .font(.headline)
                    .foregroundColor(.white)
            }
        }


    case .accessoryInline:
        Text("🌱")
        
    case .systemMedium:
        
        ZStack {
            Color.white // set background color
            
            VStack {
                if let barcodeImage = generateBarcode(from: entry.flutterData?.text ?? "") {
                    Image(uiImage: barcodeImage)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .padding(0)
                }
            }
        }
        
    default:
        Text("error")
    }

    
    
    
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant