Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

App Store Review Request error Swift 6
I'm fairly new to Swift, so I'm unsure as to what's going wrong with my code and how to fix it. After switching to Swift 6, the view I have with requestReview throws: "Cannot form key path to main actor-isolated property 'requestReview'" As I understand it, this is potentially due to the changes made to @MainActor. However, I am unsure how to go about fixing this error.
3
2
95
1d
Type '' does not conform to protocol '_IntentValue' - AppIntents
Hi there. First time poster! I'm attempting to implement App Intents in my app, as part of the App Intent I have included a parameter requiring the user specify one of their 'to do lists'. @Parameter(title: "List", description: "One of your Marvelist lists.") var list: MarvelistModels.List However, I'm receiving the below error in Xcode... Type 'MarvelistModels.List' does not conform to protocol '_IntentValue' When I go to the struct for MarvelistModels.List, and attempt to make it conform to _IntentValue, it adds typealias Specification = type to my struct... however, I can't quite figure out how to make it conform. Any help/advice would be greatly appreicated!
0
1
120
6d
How to show icons apps when retrieving DeviceActivityReport
Actually, I'm developing a new app based on screen time API, so I implemented my report device extension like this struct TotalActivityReport: DeviceActivityReportScene { // Define which context your scene will represent. let context: DeviceActivityReport.Context = .totalActivity // Define the custom configuration and the resulting view for this report. let content: (ActivityReport) -> TotalActivityView func makeConfiguration(representing data: DeviceActivityResults<DeviceActivityData>) async -> ActivityReport { // Reformat the data into a configuration that can be used to create // the report's view. var res = "" var list: [AppDeviceActivity] = [] let totalActivityDuration = await data.flatMap { $0.activitySegments }.reduce(0, { $0 + $1.totalActivityDuration }) for await d in data { res += d.user.appleID!.debugDescription res += d.lastUpdatedDate.description for await a in d.activitySegments{ res += a.totalActivityDuration.formatted() for await c in a.categories { for await ap in c.applications { let appName = (ap.application.localizedDisplayName ?? "nil") let bundle = (ap.application.bundleIdentifier ?? "nil") let duration = ap.totalActivityDuration let numberOfPickups = ap.numberOfPickups let token = ap.application.token let app = AppDeviceActivity( id: bundle, displayName: appName, duration: duration, numberOfPickups: numberOfPickups, token: token ) list.append(app) } } } } return ActivityReport(totalDuration: totalActivityDuration, apps: list) } } Then TotalActivityView to visualize returned data like this // // TotalActivityView.swift // DemoScreenTimeReporter // // Created by Achraf Trabelsi on 17/06/2024. // import SwiftUI import ManagedSettings struct TotalActivityView: View { var activityReport: ActivityReport var body: some View { VStack { Spacer(minLength: 50) Text("Total Screen Time") Spacer(minLength: 10) Text(activityReport.totalDuration.stringFromTimeInterval()) List(activityReport.apps) { app in ListRow(eachApp: app) } } } } struct ListRow: View { var eachApp: AppDeviceActivity var body: some View { HStack { Text(eachApp.displayName) Spacer() Text(eachApp.id) Spacer() Text("\(eachApp.numberOfPickups)") Spacer() Text(String(eachApp.duration.formatted())) if let appToken = eachApp.token { Label(appToken).labelStyle(.iconOnly) } } } } But I got this issue : Cannot convert value of type 'ApplicationToken' (aka 'Token') to expected argument type 'LabelStyleConfiguration' So if anyone have an idea, how can we get application icons please ?
0
0
107
1w
Sendability for Stream, InputStream, etc.
I have a project with some legacy networking code that uses the Stream (formerly NSStream) family of classes, including Stream, InputStream, OutputStream, and StreamDelegate. None of these are sendable, so I get a lot of warnings when implementing delegate methods in a @MainActor class. These classes seem like they could be sendable. Is this something that will happen soon? Is it a bug I should report? The networking code that uses these classes runs great, and hasn't needed changes for years, so my current solution is to just mark these unchecked: extension Stream: @unchecked Sendable { } extension InputStream: @unchecked Sendable { } extension OutputStream: @unchecked Sendable { } This makes the compiler happy, but makes me feel kind of bad. Is there something else I could do?
1
0
96
6d
UI Tests Runner application does not launch manually.
I need to run my tests bundle independently from Xcode. Previously, I used to deploy it and run as regular iOS application, it would execute test cases and display 'Automation running' label. I needed to execute tests some time after deploy and in different time of the day, so it is a problem for my team right now. So, UI Tests Runner app file does not launch and 'Automation Running' label is not displayed, is there any possible ways to run tests as it was or other ways to run tests not from Xcode.
0
0
85
1w
App using MetalKit creates many IOSurfaces in rapid succession, causing MTKView to freeze and app to hang
I've got an iOS app that is using MetalKit to display raw video frames coming in from a network source. I read the pixel data in the packets into a single MTLTexture rows at a time, which is drawn into an MTKView each time a frame has been completely sent over the network. The app works, but only for several seconds (a seemingly random duration), before the MTKView seemingly freezes (while packets are still being received). Watching the debugger while my app was running revealed that the freezing of the display happened when there was a large spike in memory. Seeing the memory profile in Instruments revealed that the spike was related to a rapid creation of many IOSurfaces and IOAccelerators. Profiling CPU Usage shows that CAMetalLayerPrivateNextDrawableLocked is what happens during this rapid creation of surfaces. What does this function do? Being a complete newbie to iOS programming as a whole, I wonder if this issue comes from a misuse of the MetalKit library. Below is the code that I'm using to render the video frames themselves: class MTKViewController: UIViewController, MTKViewDelegate { /// Metal texture to be drawn whenever the view controller is asked to render its view. private var metalView: MTKView! private var device = MTLCreateSystemDefaultDevice() private var commandQueue: MTLCommandQueue? private var renderPipelineState: MTLRenderPipelineState? private var texture: MTLTexture? private var networkListener: NetworkListener! private var textureGenerator: TextureGenerator! override public func loadView() { super.loadView() assert(device != nil, "Failed creating a default system Metal device. Please, make sure Metal is available on your hardware.") initializeMetalView() initializeRenderPipelineState() networkListener = NetworkListener() textureGenerator = TextureGenerator(width: streamWidth, height: streamHeight, bytesPerPixel: 4, rowsPerPacket: 8, device: device!) networkListener.start(port: NWEndpoint.Port(8080)) networkListener.dataRecievedCallback = { data in self.textureGenerator.process(data: data) } textureGenerator.onTextureBuiltCallback = { texture in self.texture = texture self.draw(in: self.metalView) } commandQueue = device?.makeCommandQueue() } public func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { /// need implement? } public func draw(in view: MTKView) { guard let texture = texture, let _ = device else { return } let commandBuffer = commandQueue!.makeCommandBuffer()! guard let currentRenderPassDescriptor = metalView.currentRenderPassDescriptor, let currentDrawable = metalView.currentDrawable, let renderPipelineState = renderPipelineState else { return } currentRenderPassDescriptor.renderTargetWidth = streamWidth currentRenderPassDescriptor.renderTargetHeight = streamHeight let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: currentRenderPassDescriptor)! encoder.pushDebugGroup("RenderFrame") encoder.setRenderPipelineState(renderPipelineState) encoder.setFragmentTexture(texture, index: 0) encoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: 1) encoder.popDebugGroup() encoder.endEncoding() commandBuffer.present(currentDrawable) commandBuffer.commit() } private func initializeMetalView() { metalView = MTKView(frame: CGRect(x: 0, y: 0, width: streamWidth, height: streamWidth), device: device) metalView.delegate = self metalView.framebufferOnly = true metalView.colorPixelFormat = .bgra8Unorm metalView.contentScaleFactor = UIScreen.main.scale metalView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.insertSubview(metalView, at: 0) } /// initializes render pipeline state with a default vertex function mapping texture to the view's frame and a simple fragment function returning texture pixel's value. private func initializeRenderPipelineState() { guard let device = device, let library = device.makeDefaultLibrary() else { return } let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.rasterSampleCount = 1 pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm pipelineDescriptor.depthAttachmentPixelFormat = .invalid /// Vertex function to map the texture to the view controller's view pipelineDescriptor.vertexFunction = library.makeFunction(name: "mapTexture") /// Fragment function to display texture's pixels in the area bounded by vertices of `mapTexture` shader pipelineDescriptor.fragmentFunction = library.makeFunction(name: "displayTexture") do { renderPipelineState = try device.makeRenderPipelineState(descriptor: pipelineDescriptor) } catch { assertionFailure("Failed creating a render state pipeline. Can't render the texture without one.") return } } } My question is simply: what gives?
0
0
146
1w
Autofill multiply SecureFields issue in SwiftUI view
Hello forums, I have a problem with Autofill multiply SecureFields. I created a SwiftUI view with 2 SecureFields, createPassword and confirmPassword. Does not matter how I change the textContentType, AutoFill will only fill the first SecureField. For testing, I set the first SecureField textContentType to .none / .userName/ .email, and second SecureField sets to .newPassword, but AutoFill still fills password in first SecureField. As I know Apple advises to put both SecureField textContentType to .newPassword but it seems only working in UIKit: Enabling Password AutoFill on a text input view struct ContentView: View { @State private var createPassword = "" @State private var confirmPassword = "" var body: some View { VStack { SecureField("Password", text: $createPassword) .textContentType(.newPassword) SecureField("Password confirmation", text: $confirmPassword) .textContentType(.newPassword) } .padding() } } Thank you!
0
0
122
1w
Understanding Syncing between Core Data and CloudKit Public Database using NSPersistantCloudKitContainer
Can someone please give me an overview of how sync works between Core Data and the public CloudKit database when using the NSPersistentCloudKitContainer and please point out my misunderstandings based on what I describe below? In the following code, I'm successfully connecting to the public database in CloudKit using the NSPersistentCloudKitContainer. Below is how I have Core Data and CloudKit set up for your reference. In CloudKit I have a set of PublicIconImage that I created manually via the CloudKit Console. I intend to be able to download all images from the public database at the app launch to the local device and manage them via Core Data to minimize server requests, which works but only if the user is logged in. This is the behavior I see: When the app launches, all the CloudKit images get mirrored to Core Data and displayed on the screen but only if the user is logged in with the Apple ID, otherwise nothing gets mirrored. What I was expecting: I was under the impression that when connecting to the public database in CloudKit you didn't need to be logged in to read data. Now, if the user is logged in on the first launch, all data is successfully mirrored to Core Data, but then if the user logs off, all data previously mirrored gets removed from Core Data, and I was under the impression that since Core Data had the data already locally, it would keep the data already downloaded regardless if it can connect to CloudKit or not. What am I doing wrong? Core Data Model: Entity: PublicIconImage Attributes: id (UUID), imageName (String), image (Binary Data). CloudKit Schema in Public Database: Record: CD_PublicIconImage Fields: CD_id (String), CD_imageName (String), CD_image (Bytes). Core Data Manager class CoreDataManager: ObservableObject{ // Singleton static let instance = CoreDataManager() private let queue = DispatchQueue(label: "CoreDataManagerQueue") private var iCloudSync = true lazy var context: NSManagedObjectContext = { return container.viewContext }() lazy var container: NSPersistentContainer = { return setupContainer() }() func updateCloudKitContainer() { queue.sync { container = setupContainer() } } func setupContainer()->NSPersistentContainer{ let container = NSPersistentCloudKitContainer(name: "CoreDataContainer") guard let description = container.persistentStoreDescriptions.first else{ fatalError("###\(#function): Failed to retrieve a persistent store description.") } description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) let cloudKitContainerIdentifier = "iCloud.com.example.PublicDatabaseTest" let options = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitContainerIdentifier) description.cloudKitContainerOptions = options description.cloudKitContainerOptions?.databaseScope = .public // Specify Public Database container.loadPersistentStores { (description, error) in if let error = error{ print("Error loading Core Data. \(error)") } } container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return container } func save(){ do{ try context.save() }catch let error{ print("Error saving Core Data. \(error.localizedDescription)") } } } View Model Class class PublicIconImageViewModel: ObservableObject { let manager: CoreDataManager @Published var publicIcons: [PublicIconImage] = [] init(coreDataManager: CoreDataManager = .instance) { self.manager = coreDataManager loadPublicIcons() } func loadPublicIcons() { let request = NSFetchRequest<PublicIconImage>(entityName: "PublicIconImage") let sort = NSSortDescriptor(keyPath: \PublicIconImage.imageName, ascending: true) request.sortDescriptors = [sort] do { publicIcons = try manager.context.fetch(request) } catch let error { print("Error fetching PublicIconImages. \(error.localizedDescription)") } } } SwiftUI View struct ContentView: View { @EnvironmentObject private var publicIconViewModel: PublicIconImageViewModel var body: some View { VStack { List { ForEach(publicIconViewModel.publicIcons) { icon in HStack{ Text(icon.imageName ?? "unknown name") Spacer() if let iconImageData = icon.image, let uiImage = UIImage(data: iconImageData) { Image(uiImage: uiImage) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 35, height: 35) } } } } .onAppear { // give some time to get the images downlaoded DispatchQueue.main.asyncAfter(deadline: .now() + 5){ publicIconViewModel.loadPublicIcons() } } } .padding() } }
0
0
85
1w
UI not dynamically updating from push notifications fetchdata function
Hi All, I really need your help, I have been racking my brain to work out why, after a push notification triggers a fetchdata function from the server, my new bookings dont dynamically update the counter against the booking types. print("Received remote notification: \(userInfo)") if let dataInfo = userInfo["data"] as? [String: Any], let jsonData = try? JSONSerialization.data(withJSONObject: dataInfo) { print("Processing data from notification...") DispatchQueue.main.async { self.eventsViewModel.updateFromPushNotification(data: jsonData) { result in completionHandler(result) } } } else { print("Failed to parse notification data") completionHandler(.noData) } } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Failed to register for remote notifications: \(error)") } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { print("Will present notification: \(notification.request.content.userInfo)") DispatchQueue.main.async { self.eventsViewModel.fetchData() } completionHandler([.banner, .badge, .sound]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("Did receive notification response: \(response.notification.request.content.userInfo)") let userInfo = response.notification.request.content.userInfo if let fetchNeeded = userInfo["fetchNeeded"] as? Bool, fetchNeeded { print("Initiating data fetch due to user interaction...") DispatchQueue.main.async { self.eventsViewModel.fetchData() } } completionHandler() } @Published var bookings: [AnyBooking] = [] @Published var newBookings: [AnyBooking] = [] @Published var calendarBookings: [String: [AnyBooking]] = [:] @Published var selectedBooking: AnyBooking? private var cancellables = Set<AnyCancellable>() private let calendarManager = CalendarManager.shared // Add calendarManager func fetchData() { guard let url = URL(string: "https://allsound.wisewms.uk/webhook_get") else { print("Invalid URL for webhook request") return } var request = URLRequest(url: url) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request) { [weak self] (data, response, error) in guard let self = self else { return } if let error = error { print("Error fetching data: \(error.localizedDescription)") return } if let data = data, !data.isEmpty { if let newBookings = self.processBookings(data: data) { DispatchQueue.main.async { self.bookings = newBookings self.separateAndOrganizeBookings(bookings: newBookings) } } else { print("Failed to process bookings.") } } else { print("No data received from server.") } } task.resume() } @main struct AllSoundApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate @StateObject var eventsViewModel = EventsViewModel() @Environment(\.scenePhase) var scenePhase @AppStorage("selectedTheme") private var selectedTheme: Theme = .system var body: some Scene { WindowGroup { ContentView() .environmentObject(eventsViewModel) .environmentObject(appDelegate.navigationCoordinator) .preferredColorScheme(selectedTheme.colorScheme) .onChange(of: scenePhase) { oldPhase, newPhase in if newPhase == .active { eventsViewModel.fetchData() } } } } }
2
0
110
1w
SwiftData migration error
CrashLog Distributor ID: com.apple.AppStore Hardware Model: iPhone15,3 Process: DeadLineTodo [5556] Path: /private/var/containers/Bundle/Application/348CC8D5-05FD-41DF-93A3-C15562EF4AA8/DeadLineTodo.app/DeadLineTodo Identifier: andy.DeadLineTodo Version: 2.4.0 (3) AppStoreTools: 15F31e AppVariant: 1:iPhone15,3:17 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: andy.DeadLineTodo [2089] Date/Time: 2024-06-08 19:13:53.6259 +0800 Launch Time: 2024-06-08 19:13:53.2839 +0800 OS Version: iPhone OS 17.5.1 (21F90) Release Type: User Baseband Version: 2.60.02 Report Version: 104 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x0000000195a2d8c0 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [5556] Triggered by Thread: 0 Thread 0 name: Thread 0 Crashed: 0 libswiftCore.dylib 0x0000000195a2d8c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144) 1 DeadLineTodo 0x0000000100dde700 DeadLineTodoApp.init() + 1140 (DeadLineTodoApp.swift:46) 2 DeadLineTodo 0x0000000100ddef30 protocol witness for App.init() in conformance DeadLineTodoApp + 28 (<compiler-generated>:0) 3 SwiftUI 0x000000019b2c84c0 static App.main() + 116 (App.swift:114) 4 DeadLineTodo 0x0000000100ddeec4 static DeadLineTodoApp.$main() + 40 (<compiler-generated>:0) 5 DeadLineTodo 0x0000000100ddef5c main + 12 (DeadLineTodoApp.swift:32) 6 dyld 0x00000001ba7d1e4c start + 2240 (dyldMain.cpp:1298) Thread 1: 0 libsystem_pthread.dylib 0x00000001f3fa40c4 start_wqthread + 0 (:-1) Thread 2: 0 libsystem_pthread.dylib 0x00000001f3fa40c4 start_wqthread + 0 (:-1) Thread 0 crashed with ARM Thread State (64-bit): x0: 0x8000000100f01ad0 x1: 0x0000000000000000 x2: 0x0000000000000000 x3: 0x00000003019e9bc0 x4: 0x0000000000000000 x5: 0x000000016f16f3e0 x6: 0x000000000000002e x7: 0x0000000000000000 x8: 0x0000000000000100 x9: 0x00000000000000ff x10: 0x0000000000001b80 x11: 0x00000000f3444870 x12: 0x00000000000007fb x13: 0x00000000000007fd x14: 0x00000000f364506f x15: 0x000000000000006f x16: 0x00000000f3444870 x17: 0x0000000000045000 x18: 0x0000000000000000 x19: 0x0000000100f01dba x20: 0x8000000100f01ad0 x21: 0x0000000000000000 x22: 0x000000000000000b x23: 0x0000000000000022 x24: 0x000000000000002e x25: 0x0000000100f01ac0 x26: 0xd000000000000025 x27: 0x0000000000000000 x28: 0x0000000000000000 fp: 0x000000016f16f5c0 lr: 0x0000000195a2d8c0 sp: 0x000000016f16f4f0 pc: 0x0000000195a2d8c0 cpsr: 0x60001000 esr: 0xf2000001 (Breakpoint) brk 1 Binary Images: 0x100c90000 - 0x100f0ffff DeadLineTodo arm64 <c16650393d4537299a08b798b8227d31> /private/var/containers/Bundle/Application/348CC8D5-05FD-41DF-93A3-C15562EF4AA8/DeadLineTodo.app/DeadLineTodo 0x101214000 - 0x10121ffff libobjc-trampolines.dylib arm64e <2e2c05f8377a30899ad91926d284dd03> /private/preboot/Cryptexes/OS/usr/lib/libobjc-trampolines.dylib 0x1959f4000 - 0x195f43fff libswiftCore.dylib arm64e <d9ad5cc1ca2c3f0a8091652b0df56d14> /usr/lib/swift/libswiftCore.dylib 0x19af1c000 - 0x19ccbafff SwiftUI arm64e <c1325fda9da239d2ab83a338b4d8a884> /System/Library/Frameworks/SwiftUI.framework/SwiftUI 0x1ba795000 - 0x1ba821ef7 dyld arm64e <71846eacee653697bf7d790b6a07dcdb> /usr/lib/dyld 0x1f3fa3000 - 0x1f3fafff3 libsystem_pthread.dylib arm64e <1196b6c3333d3450818ff3663484b8eb> /usr/lib/system/libsystem_pthread.dylib EOF DeadLineTodoApp.swift import SwiftUI import SwiftData typealias TodoData = TodoDataSchemaV8.TodoData typealias UserSetting = TodoDataSchemaV8.UserSetting enum TodoDataMigrationPlan: SchemaMigrationPlan { static var schemas: [VersionedSchema.Type] { [TodoDataSchemaV1.self, TodoDataSchemaV2.self, TodoDataSchemaV3.self, TodoDataSchemaV4.self, TodoDataSchemaV5.self, TodoDataSchemaV6.self, TodoDataSchemaV7.self, TodoDataSchemaV8.self] } static var stages: [MigrationStage]{ [migrationV1toV2, migrationV2toV3, migrationV3toV4, migrationV4toV5, migrationV5toV6, migrationV6toV7, migrationV7toV8] } static let migrationV1toV2 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV1.self, toVersion: TodoDataSchemaV2.self) static let migrationV2toV3 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV2.self, toVersion: TodoDataSchemaV3.self) static let migrationV3toV4 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV3.self, toVersion: TodoDataSchemaV4.self) static let migrationV4toV5 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV4.self, toVersion: TodoDataSchemaV5.self) static let migrationV5toV6 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV5.self, toVersion: TodoDataSchemaV6.self) static let migrationV6toV7 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV6.self, toVersion: TodoDataSchemaV7.self) static let migrationV7toV8 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV7.self, toVersion: TodoDataSchemaV8.self) } @main struct DeadLineTodoApp: App { let container: ModelContainer @StateObject var store = StoreKitManager() @State var updated: Bool = false init() { do { container = try ModelContainer( for: TodoData.self, UserSetting.self, migrationPlan: TodoDataMigrationPlan.self) } catch { print("初始化模型容器时发生错误:\(error)") fatalError("Failed to initialize model container.") } } var body: some Scene { WindowGroup { ContentView(updated: $updated) .environmentObject(store) } .modelContainer(container) } }
0
0
103
1w
JSON Encoder Crashing
Hi For some of the user the JSON Encoder is giving crash while converting array of Models into the dictionary its not reproducible at our end. Below is the stack trace of the issue 2024-06-14_21-18-38.4054_-0500-90aad9908d4fb2c7b8e49ce4b3025fab79674e31.crash Please help with above crash how can we reproduce and what should be the solution for this. Thanks
1
0
122
1w
PHP doesn't show images in WKWebView
Since httpRequest body is ignored on WKWebView, I am trying to display a php page by fetching the data first, and displaying it. func fetchData() { URLSession.shared.dataTask(with: request) {(data, response, error) in guard let data, let url = request.url else { return } // pass the result to WKWebView }.resume() } import Foundation import SwiftUI import WebKit struct CustomWebView: UIViewRepresentable { var url: URL var data: Data func makeUIView(context: Context) -> UIView { return CustomUIWebView(url: url, data: data) } } class CustomUIWebView: UIView { let webView: WKWebView init(url: URL,data:Data) { let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: .zero, configuration: webConfiguration) super.init(frame: .zero) webView.load(data, mimeType: "text/html", characterEncodingName: "utf-8", baseURL: url) addSubview(webView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() webView.frame = bounds } The data contains the page that display several images, but it doesn't display any of the images in WKWebView. Test and other components (such as checkmark button) have no problem, only images do. Also, I confirmed it works fine on Safari. So what is the issue here? What am I doing wrong?
0
0
67
1w
How to determine that NWBrowser has finished?
I am using NWBrowser to detect SignalK servers on a network using the following Swift code: let browser = NWBrowser(for: .bonjourWithTXTRecord(type: "_http._tcp", domain: nil), using: NWParameters()) browser.browseResultsChangedHandler = { results, changes in print("Found \(results.count) results and \(changes.count) changes") } When this is run on a network with 5 devices then the output is often Found 5 results and 5 changes But, sometime it is: Found 2 results and 2 changes Found 5 results and 3 changes indicating that the browseResultsChangedHandler is being called more than once. So my question is how do I determine when the browsing process has finished (obviously without the knowledge that there are 5 devices)? The depreciated NetServiceBrowser had a delegate method (netServiceBrowser(_:didFind:moreComing:) but I can't see an equivalent for NWBrowser. The only method I can think of is to apply a short time out.
3
0
111
1w
SwiftData fatal error: Failed to locate relationship for StringCodingKey
I'm experiencing a new error in SwiftData since updating to Xcode 16/iOS 17 DB1. When passing in a model (Student) to a view and then displaying an array of Points using ForEach, I get the following fatal error: SwiftData/ModelCoders.swift:2438: Fatal error: Failed to locate relationship for StringCodingKey(stringValue: "group", intValue: nil) on Entity - name: Point superentity: subentities: storedProperties: CompositeAttribute - name: type, options: [], valueType: PointType, defaultValue: nil Properties: Attribute - name: type, options: [], valueType: String, defaultValue: nil, hashModifier: nil Relationship - name: outcome, options: [], valueType: Outcome, destination: Outcome, inverseName: nil, inverseKeypath: nil CompositeAttribute - name: proficiency, options: [], valueType: Proficiency, defaultValue: nil Properties: Attribute - name: proficiency, options: [], valueType: String, defaultValue: nil, hashModifier: nil Attribute - name: date, options: [], valueType: Date, defaultValue: nil, hashModifier: nil Attribute - name: note, options: [], valueType: String, defaultValue: nil, hashModifier: nil Relationship - name: student, options: [], valueType: Optional<Student>, destination: Student, inverseName: points, inverseKeypath: Optional(\Student.points) Attribute - name: group, options: [], valueType: Array<PersistentIdentifier>, defaultValue: [], hashModifier: nil inheritedProperties: uniquenessConstraints: indices: Xcode flags this line of the macro-generated getter of the outcome property on Point: @storageRestrictions(accesses: _$backingData, initializes: _outcome) init(initialValue) { _$backingData.setValue(forKey: \.outcome, to: initialValue) _outcome = _SwiftDataNoType() } get { _$observationRegistrar.access(self, keyPath: \.outcome) return self.getValue(forKey: \.outcome) // Fatal error: Failed to locate relationship for StringCodingKey... } set { _$observationRegistrar.withMutation(of: self, keyPath: \.outcome) { self.setValue(forKey: \.outcome, to: newValue) } } This worked just fine in iOS 17. Here's a snippet of the Student implementation: @Model class Student: Identifiable, Comparable { var name: String var number: Int @Relationship(deleteRule: .cascade, inverse: \Point.student) var points: [Point] @Relationship(deleteRule: .cascade, inverse: \Mark.student) var marks: [Mark] @Relationship(deleteRule: .nullify, inverse: \StudentGroup.students) var groups: [StudentGroup] = [] var archived: Bool } and the implementation of Point: @Model class Point: Identifiable, Comparable { var student: Student? var type: PointType var outcome: Outcome var proficiency: Proficiency var group: [Student.ID] = [] var date: Date var note: String } and finally the implementation for Outcome: @Model class Outcome: Identifiable, Comparable { var name: String var index: Int var rubric: Rubric? var proficiencies: [Proficiency] } I've tried adding a relationship in Outcome as an inverse of the outcomes property on Points (although this does not make sense in my implementation, which is why I initially did not set a relationship here) and the problem persisted. Any ideas what this error means and how I might go about fixing it?
0
0
110
1w
TipKit vs. Swift 6 + Concurrency
I'm trying to convert my project to use Swift 6 with Complete Concurrency in Xcode 16 beta 1. The project uses TipKit, but I'm getting compile errors when trying to use the TipKit Parameters feature. Here is an example of the type of error I'm seeing (Note that this code from https://developer.apple.com/documentation/tipkit/highlightingappfeatureswithtipkit): struct ParameterRuleTip: Tip { // Define the app state you want to track. @Parameter static var isLoggedIn: Bool = false Static property '$isLoggedIn' is not concurrency-safe because it is non-isolated global shared mutable state. Is there a new pattern for supporting TipKit Parameters in Swift 6 with Complete Concurrency enabled? There is no obvious suggestion for how to fix this. The latest WWDC 2024 TipKit doesn't appear to have any solution(s).
6
2
186
10h
How to set up multi platform efficiently
Hello, so I have a SwiftUI app that is relatively large, and it has multiple targets, one for each platform. but as I near App Store release I'm feeling very confused as to how to configure it. One app was rejected because the Mac target's name becomes the app which is different from App Store (Texty+ [App Store] vs Texty+ Mac [on target]). So I then just combined all the files into one target with a #if os(Mac... iOS) etc, but is that the proper way for multi platform app. I know there is like a Multiplatform target but that would require I restructure all the files and that always leads to issues in this near release app.
1
0
122
1w
SwiftData History Tombstone Data is Unusable
After watching the WWDC video on the new history tracking in SwiftData, I started to update my app with this functionality. Unfortunately it seems that the current API in the first beta of Xcode 16 is rather useless in regards to tombstone data. The docs state that it would be possible to get the data from the tombstone by using a keyPath, there is no API for this however. The only thing I can do is iterate over the values (of type any) without any key information, so I do not know which data is what. Am I missing something or did we get a half finished implementation? There also does not seem to be any info on this in the release notes.
1
0
111
1w
SwiftData crashes on insert (Swift 6, Xcode 16, macOS 15)
I'm trying to insert values into my SwiftData container but it crashes on insert context.insert(fhirObject) and the only error I get from Xcode is: @Transient private var _hkID: _SwiftDataNoType? // original-source-range: /Users/cyril/Documents/GitHub/MyApp/MyApp/HealthKit/FHIR/FHIRModels.swift:35:20-35:20 configured as follows: import SwiftData import SwiftUI @main struct MyApp: App { var container: ModelContainer init() { do { let config = ModelConfiguration(cloudKitDatabase: .private("iCloud.com.author.MyApp")) container = try ModelContainer(for: FHIRObservation.self, configurations: config) UserData.shared = UserData(modelContainer: container) } catch { fatalError("Failed to configure SwiftData container.") } } var body: some Scene { WindowGroup { ContentView() .environmentObject(UserData.shared) } .modelContainer(container) } } My UserData and DataStore are configured as follows: import SwiftUI import SwiftData import os /// `FHIRDataStore` is an actor responsible for updating the SwiftData db as needed on the background thread. private actor FHIRDataStore { let logger = Logger( subsystem: "com.author.MyApp.FHIRDataStore", category: "ModelIO") private let container: ModelContainer init(container: ModelContainer) { self.container = container } func update(newObservations: [FHIRObservationWrapper], deletedObservations: [UUID]) async throws { let context = ModelContext(container) // [FHIRObservationWrapper] -> [FHIRObservation] // let modelUpdates = newObservations.lazy.map { sample in // FHIRObservation(hkID: sample.hkID, fhirID: sample.fhirID, name: sample.name, status: sample.status, code: sample.code, value: sample.value, range: sample.range, lastUpdated: sample.lastUpdated) // } do { try context.transaction { for sample in newObservations { let fhirObject = FHIRObservation(hkID: sample.hkID, fhirID: sample.fhirID, name: sample.name, status: sample.status, code: sample.code, value: sample.value, range: sample.range, lastUpdated: sample.lastUpdated) // App crashes here context.insert(fhirObject) } // for obj in modelUpdates { // // } // try context.delete(model: FHIRObservation.self, where: #Predicate { sample in // deletedObservations.contains(sample.hkID!) // }) // try context.save() logger.debug("Database updated successfully with new and deleted observations.") } } catch { logger.debug("Catch me bro: \(error.localizedDescription)") } } } @MainActor public class UserData: ObservableObject { let userDataLogger = Logger( subsystem: "com.author.MyApp.UserData", category: "Model") public static var shared: UserData! // MARK: - Properties public lazy var healthKitManager = HKManager(withModel: self) let modelContainer: ModelContainer private var store: FHIRDataStore init(modelContainer: ModelContainer) { self.modelContainer = modelContainer self.store = FHIRDataStore(container: modelContainer) } // MARK: - Methods func updateObservations(newObservations: [FHIRObservationWrapper], deletedObservations: [UUID]) { Task { do { try await store.update(newObservations: newObservations, deletedObservations: deletedObservations) userDataLogger.debug("Observations updated successfully.") } catch { userDataLogger.error("Failed to update observations: \(error.localizedDescription)") } } } } My @Model is configured as follows: public struct FHIRObservationWrapper: Sendable { let hkID: UUID let fhirID: String var name: String var status: String var code: FHIRCodeableConcept var value: FHIRLabValueType var range: FHIRLabRange? var lastUpdated: Date? } @Model public final class FHIRObservation { let hkID: UUID? let fhirID: String? @Attribute(.allowsCloudEncryption) var name: String? @Attribute(.allowsCloudEncryption) var status: String? @Attribute(.allowsCloudEncryption) var code: FHIRCodeableConcept? @Attribute(.allowsCloudEncryption) var value: FHIRLabValueType? @Attribute(.allowsCloudEncryption) var range: FHIRLabRange? @Attribute(.allowsCloudEncryption) var lastUpdated: Date? init(hkID: UUID?, fhirID: String?, name: String? = nil, status: String? = nil, code: FHIRCodeableConcept? = nil, value: FHIRLabValueType? = nil, range: FHIRLabRange? = nil, lastUpdated: Date? = nil) { self.hkID = hkID self.fhirID = fhirID self.name = name self.status = status self.code = code self.value = value self.range = range self.lastUpdated = lastUpdated } } Any help would be greatly appreciated!
2
0
173
1w