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

Why does my universal links not work??
I implemented a universal link according to this guidance. https://developer.apple.com/videos/play/wwdc2019/717 However, my universal links seem to never work. apple-app-site-association https://hajimenavi.web.app/.well-known/apple-app-site-association Xcode settings The link I am trying to open https://hajimenavi.web.app/familyId/ZBEJSJXyPNT7G team id I validated with apple's analyzation that the server has no problem (with Setting app>Developer>Universal Links analysis. What else should I check?? I am wasting a whole day with this. Please please help.
4
0
70
2h
API naming consistency
Why it is so difficult for Apple dev team to maintain consistent naming of their APIs? The function is called fatalError(_:file:line:) The corresponding Loogger.Level is called critical. Why not fatal? Is Ali Ozer still working at Apple to kick the a*s of new developers? I do not assume that either the function or the log level will be renamed. But I hope someone will take care of details (in the future). P.S. I am developing on NeXTStep since 1990. There were times when APIs were so consistent, one could guess them almost 100% correctly. It will benefit the community if this would be true today as well.
0
0
26
15h
Concurrency-friendly version of `ArchiveByteStream` and `ArchiveStream`?
The AppleArchive module is pretty cool, but it relies almost entirely on two stream types, ArchiveByteStream and ArchiveStream, which don't really work well in a Swift Concurrency-based workflow since they all use thread-blocking mechanisms like pthread mutexes for synchronization, and threads in the cooperative pool should not be blocked. They also use their own thread pools for processing, independently of the cooperative thread pool, making it easy to end up with more threads than one has cores. (Perhaps even more so if you try to compress/decompress multiple files at once? The documentation isn't clear on whether separate archive operations share the same thread pool or not, but since it allows you to choose the size of the pool, it seems that these may be separate from each other as well.) Are there any plans for an interface to Apple Archive that would fit better with the structured concurrency model?
1
0
58
1d
Create ML "Unexpected Error" During Hand Action Classification Training
I have created a Hand Action Classification project following the guidelines which causes the Create ML tool to provide the very cryptic "Unexpected Error". The feature extraction phase is fine, with the error occurring during model training after the tool reports completion of the first five training iterations as it moves on to report the next ten. The project is small with 3 training classes and 346 items I have tried to vary the frame rate and action duration, with all augmentations unset, but the error still persists. Can you please confirm how I may get further error diagnostic information so that I can determine why Create ML is unable to work with my training data? Mac OS is Sonoma 14.5 on an iMac 24-inch, M1, 2021. Create ML is Version 5.0 (121.4)
0
0
28
1d
Can't write a property through ScriptingBridge
Staring to use ScriptingBridge in Swift to enable faster scripting access to an external app (Devonthink) and therefore avoid having to use an AppleScript as a conduit to call a Swift command line utility and deal with its results. The plan is to be able to read the plaintext of a record (no problem) and change the record name in Devonthink based on its contents. But I can’t seem to write to a property, instead getting an error “Cannot assign to property: ‘***’ is immutable”. Any guidance how to get around this?
0
0
38
19h
Sheet Presentation
Hi, would appreciate based on my implementation how can I control the dimmed effect of sheet presentation on iOS 17 later. Here is my sample implementation: struct ContentView: View { @State private var present = true var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() .sheet(isPresented: $present, content: { ContentView2() .modifier( SheetModifier( dismissDisabled: true, detents: [.medium, .large], dragIndicator: .hidden ) ) }) } } #Preview { ContentView() } struct SheetModifier: ViewModifier { var dismissDisabled: Bool var detents: Set<PresentationDetent> var backgroundInteraction: PresentationBackgroundInteraction var dragIndicator: Visibility var cornerRadius: CGFloat init( dismissDisabled: Bool = false, detents: Set<PresentationDetent>, backgroundInteraction: PresentationBackgroundInteraction = .automatic, dragIndicator: Visibility = .automatic, cornerRadius: CGFloat = 20 ) { self.dismissDisabled = dismissDisabled self.detents = detents self.backgroundInteraction = backgroundInteraction self.dragIndicator = dragIndicator self.cornerRadius = cornerRadius } func body(content: Content) -> some View { content .background(.clear) .interactiveDismissDisabled(dismissDisabled) .presentationDetents(detents) .presentationBackgroundInteraction(backgroundInteraction) .presentationDragIndicator(dragIndicator) .presentationCornerRadius(cornerRadius) } }
0
0
65
1d
SwiftData FatalError Unknown Relationship Key
Some of our users on iOS 17.5+ started to encounter crash due to: SwiftData/BackingData.swift:669: Fatal error: Unknown Relationship Key - subscription) We have tried using SwiftData on the MainActor only but an issues still effects some of our users. Our models look like these: @Model public final class ProfileModel { public static let fetchDescriptor = FetchDescriptor<ProfileModel>.self public enum Gender: Codable { case female case male case other } public enum Units: Codable { case imperial case metric } public enum Eating: Codable { case empath case enthusiast case explorer case guardian case harmonizer case pacifier case regulator case stoic case iosDefault } public enum RegistrationSource: Codable { case iOS case web } public enum NHE: Codable { case combined case emotional case mindless } public enum Goal: Codable { case beHealthier case energyIncrease case healthyHabits case looseWeight case relationshipsWithFood } public enum WeightLossFocus: Codable { case activity case healthyHabits case nutrition case other } @Attribute(.unique) public let id: String public let isPaid: Bool public let eating: Eating public let registrationSource: RegistrationSource public let nhe: NHE? public let firstName: String? public let lastName: String? public let gender: Gender? public let height: String? public let age: Int? public let weight: String? public let targetWeight: String? public let bmi: String? public let goal: Goal? public let units: Units? public let weightLossFocus: WeightLossFocus? @Relationship(deleteRule: .cascade) public var subscription: ProfileSubscriptionModel? public init( id: String, isPaid: Bool, eating: Eating, registrationSource: RegistrationSource, nhe: NHE?, firstName: String?, lastName: String?, gender: Gender?, height: String?, age: Int?, weight: String?, targetWeight: String?, bmi: String?, goal: Goal?, units: Units?, weightLossFocus: WeightLossFocus?, subscription: ProfileSubscriptionModel? ) { self.id = id self.isPaid = isPaid self.eating = eating self.registrationSource = registrationSource self.nhe = nhe self.firstName = firstName self.lastName = lastName self.gender = gender self.height = height self.age = age self.weight = weight self.targetWeight = targetWeight self.bmi = bmi self.goal = goal self.units = units self.weightLossFocus = weightLossFocus self.subscription = subscription } } @Model public final class ProfileSubscriptionModel { public static let fetchDescriptor = FetchDescriptor<ProfileSubscriptionModel>.self public let price: Double public let currency: String public let period: Int public let status: String public let expirationDate: Date public let cancelledAt: Date? public init(price: Double, currency: String, period: Int, status: String, expirationDate: Date, cancelledAt: Date?) { self.price = price self.currency = currency self.period = period self.status = status self.expirationDate = expirationDate self.cancelledAt = cancelledAt } }
0
0
92
3d
Can the NSPersistentCloudKitContainer mirror the data from the cloudKit public database to the local Core Data if the user is not logged in?
I'm currently syncing Core Data with the CloudKit public database using NSPersistentCloudKitContainer. The app starts with an empty Core Data store locally and at the app launch it downloads the data from CloudKit public database to the Core Data store, but this can only be accomplished if the user is logged in, if the user is not logged, no data gets downloaded and I get the error below. Can the NSPersistentCloudKitContainer mirror the data from the CloudKit public database to the local Core Data even if the user is not logged in? Can someone please confirm this is possible? The reason for my question is because I was under the impression that the users didn't need to be logged to read data from the public database in CloudKit but I'm not sure this applies to NSPersistentCloudKitContainer when mirroring data. I know I can fetch data directly with CloudKit APIs without the user beign logged but I need to understand if NSPersistentCloudKitContainer should in theory work without the user being logged. I hope someone from Apple sees this question since I have spent too much time researching without any luck. Error Error fetching user record ID: <CKError 0x600000cb1b00: "Not Authenticated" (9); "No iCloud account is configured"> CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1192): <NSCloudKitMirroringDelegate: 0x600003b00460>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x10700f0d0> (URL: file:///Users/UserName/...
4
0
122
2d
Multiple Xcode warning messages after Xcode 15.4 / iOS 17.5 upgrade
Ever since Xcode updated yesterday I continually get the following warning message coming up on the console, with each consecutive - and identical - message highlighted in yellow & then red. The message reads: "CoreUI: _Bool CUIValidateIdiomSubtypes(NSInteger, NSUInteger *) passed a device subtype '2752' and idiom '2':pad that are not a matching pair, subtype is not valid with given idiom. Assuming subtype should be 0 instead." The program still runs but it's rather annoying, plus I'd like to know the cause. Xcode: 15.4 / iOS (in Xcode) 17.5 Any ideas?
0
0
87
4d
In App Purchases (Subscription Issue)
Hello, We are facing an issue with our customers on in-app purchasing. One of our customers tried to get a yearly subscription on 23rd May 2024 but could not succeed due to a billing error. But on 19th June 2024, his subscription was purchased automatically for 1 year, and the package expiry date shows 19th June 2025. So why did Apple charge to customer after 1 month without any intimation? Can anybody help here? Thanks
1
0
68
4d
NSFetchedResultsController - NSInvalidArgumentException
Good morning, I've developed an application where we download a JSON of objects and we store those information on a CoreData table. We've also created a Collection view used to show those information through a NSFetchedResultsController. Can someone helps me to understand the reason why I get this issue? Thanks indeed Fatal Exception: NSInvalidArgumentException 0 CoreFoundation 0x83f20 __exceptionPreprocess 1 libobjc.A.dylib 0x16018 objc_exception_throw 2 CoreFoundation 0x1b6250 _NSArrayRaiseInsertNilException 3 CoreFoundation 0x16f5c -[__NSCFArray objectAtIndex:] 4 CoreData 0x13af14 -[_PFMutableProxyArray subarrayWithRange:] 5 CoreData 0xc4948 -[_NSDefaultSectionInfo objects] 6 CoreData 0x9c3fc -[NSFetchedResultsController _conditionallyDispatchSnapshotToDelegate:updatesInfo:] 7 CoreData 0x6d4ec __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke 8 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform 9 CoreData 0x9d0ec -[NSManagedObjectContext performBlockAndWait:] 10 CoreData 0x9c6e8 -[NSFetchedResultsController _core_managedObjectContextDidChange:] 11 CoreFoundation 0x5178c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ 12 CoreFoundation 0x516a8 ___CFXRegistrationPost_block_invoke 13 CoreFoundation 0x515f0 _CFXRegistrationPost 14 CoreFoundation 0x4fbb8 _CFXNotificationPost 15 Foundation 0x31574 -[NSNotificationCenter postNotificationName:object:userInfo:] 16 CoreData 0x6a548 -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] 17 CoreData 0x69d10 -[NSManagedObjectContext _postRefreshedObjectsNotificationAndClearList] 18 CoreData 0x68a4c -[NSManagedObjectContext _processRecentChanges:] 19 CoreData 0x91494 -[NSManagedObjectContext _coreMergeChangesFromDidSaveDictionary:usingObjectIDs:withClientQueryGeneration:] 20 CoreData 0x90334 -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] 21 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform 22 libdispatch.dylib 0x3dd4 _dispatch_client_callout 23 libdispatch.dylib 0x125a4 _dispatch_main_queue_drain 24 libdispatch.dylib 0x121b8 _dispatch_main_queue_callback_4CF 25 CoreFoundation 0x56710 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ 26 CoreFoundation 0x53914 __CFRunLoopRun 27 CoreFoundation 0x52cd8 CFRunLoopRunSpecific 28 GraphicsServices 0x11a8 GSEventRunModal 29 UIKitCore 0x40a90c -[UIApplication _run] 30 UIKitCore 0x4be9d0 UIApplicationMain 31 Rainbow 0x80c0 main + 15 (main.swift:15) 32 ??? 0x1b3419e4c (Mancante)
1
0
96
4d
Crash: NSFetchedResultsController NSInvalidArgumentException
Good morning, I've developed an application in order to show the information stored into a CoraData Table on a CollectionView through a NSFetchedResultsController. Several times I got this issue, is there anyone who can help me to understand the reason why this happens? Thanks indeed. Fatal Exception: NSInvalidArgumentException 0 CoreFoundation 0x83f20 __exceptionPreprocess 1 libobjc.A.dylib 0x16018 objc_exception_throw 2 CoreFoundation 0x1b6250 _NSArrayRaiseInsertNilException 3 CoreFoundation 0x16f5c -[__NSCFArray objectAtIndex:] 4 CoreData 0x13af14 -[_PFMutableProxyArray subarrayWithRange:] 5 CoreData 0xc4948 -[_NSDefaultSectionInfo objects] 6 CoreData 0x9c3fc -[NSFetchedResultsController _conditionallyDispatchSnapshotToDelegate:updatesInfo:] 7 CoreData 0x6d4ec __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke 8 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform 9 CoreData 0x9d0ec -[NSManagedObjectContext performBlockAndWait:] 10 CoreData 0x9c6e8 -[NSFetchedResultsController _core_managedObjectContextDidChange:] 11 CoreFoundation 0x5178c CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER 12 CoreFoundation 0x516a8 ___CFXRegistrationPost_block_invoke 13 CoreFoundation 0x515f0 _CFXRegistrationPost 14 CoreFoundation 0x4fbb8 _CFXNotificationPost 15 Foundation 0x31574 -[NSNotificationCenter postNotificationName:object:userInfo:] 16 CoreData 0x6a548 -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] 17 CoreData 0x69d10 -[NSManagedObjectContext _postRefreshedObjectsNotificationAndClearList] 18 CoreData 0x68a4c -[NSManagedObjectContext _processRecentChanges:] 19 CoreData 0x91494 -[NSManagedObjectContext _coreMergeChangesFromDidSaveDictionary:usingObjectIDs:withClientQueryGeneration:] 20 CoreData 0x90334 -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] 21 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform 22 libdispatch.dylib 0x3dd4 _dispatch_client_callout 23 libdispatch.dylib 0x125a4 _dispatch_main_queue_drain 24 libdispatch.dylib 0x121b8 _dispatch_main_queue_callback_4CF 25 CoreFoundation 0x56710 CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE 26 CoreFoundation 0x53914 __CFRunLoopRun 27 CoreFoundation 0x52cd8 CFRunLoopRunSpecific 28 GraphicsServices 0x11a8 GSEventRunModal 29 UIKitCore 0x40a90c -[UIApplication _run] 30 UIKitCore 0x4be9d0 UIApplicationMain 31 Cloud 0x80c0 main + 15 (main.swift:15) 32 ??? 0x1b3419e4c (Mancante)
0
0
59
4d
SwiftUI "scaleEffect(..)" commentary
I've a SwiftUI-based app that draws into a Canvas for a complicated, dynamic rendering. Since that rendering is based on a map of the world, I transform the provided context to (±180°×±90°) longitude / latitude coordinates before stroking paths etc. Note that the necessary scaling flips the Y-axis because latitude increases up the screen. All is well until I add words to the picture. Because of the inversion of the Y-axis, the text is rendered inverted. mercatorContext.draw(Text(satellite.commonName) .font(Font(.init(.userFixedPitch, size: 4.0))) .foregroundColor(.white), at: satPoint) My solution was to draw the text via a another (un-inverted) context which corrects the words, but requires the satPoint to be flipped to place the words at the right place on the (inverted) map .. With that preamble, someone suggested I apply scaleEffect(y: -1) to the Text and avoid messing with more than one GraphicsContext. This seemed an excellent solution but it doesn't work .. context.draw(Text(.. draws a Text view but applying scaleEffect turns it into a View which context.draw can't accept. Once it's a View, I suppose I could convert it to an Image and context.draw(Image(.. instead which seems messy. I wondered about the scaleEffect function .. is it the case that it would ever actually return a view type that was different from the type it was given? Leaving my curiosity aside, what would a better way than using a second context to keep my text upright?
0
0
86
6d
Xcode memory meter goes to high while converting USDZ file to scn file by programatically
We have requirement adding usdz file to UIView and showing the it’s content and archive the data and save to file. When user open the file, we need to unarchive that usdz content and binding with UIView and showing it to user. Initially, we created SCNScene object passing usdz file url like below. do { usdzScene = try SCNScene(url: usdzUrl) } catch let error as NSError { print(error) } Since SCNScene support to NSSecureCoding protocol , we directly archive that object and save it file and load back it from file and created SCNScene object using NSKeyedUnarchiver process. But for some files, we realised high memory consumption while archiving the SCNScene object using below line. func encode(with coder: NSCoder) { coder.encode(self.scnScene, forKey: "scnScene") } File referene link : toy_drummer_idle.usdz When we analyse apple documentation (check discussion section) , it said, scn file extension is the fastest format for processing than the usdz. So we used SCNSecne write to feature for creating scn file from given usdz file. After that, When we do the archive SCNScene object that was created by sun file url, the archive process is more faster and it will not take high memory as well. It is really faster previous case now. But unfortunately, SCNScene write method will take lot of time for this conversion and memory meter is also going high and it will be caused to app crash as well. I check the output file size as well. The given usdz file size is 18MB and generated scn file size is 483 MB. But SCNScene archive process is so fast. Please, analyse this case and please, provide some guideline how we can optimise this behaviour. I really appreciate your feedback. Full Code: import UIKit import SceneKit class ViewController: UIViewController { var scnView: SCNView? var usdzScene: SCNScene? var scnScene: SCNScene? lazy var exportButton: UIButton = { let btn = UIButton(type: UIButton.ButtonType.system) btn.tag = 1 btn.backgroundColor = UIColor.blue btn.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside) btn.setTitle("USDZ to SCN", for: .normal) btn.setTitleColor(.white, for: .normal) btn.layer.borderColor = UIColor.gray.cgColor btn.titleLabel?.font = .systemFont(ofSize: 20) btn.translatesAutoresizingMaskIntoConstraints = false return btn }() func deleteTempDirectory(directoryName: String) { let tempDirectoryUrl = URL(fileURLWithPath: NSTemporaryDirectory()) let tempDirectory = tempDirectoryUrl.appendingPathComponent(directoryName, isDirectory: true) if FileManager.default.fileExists(atPath: URL(string: tempDirectory.absoluteString)!.path) { do{ try FileManager.default.removeItem(at: tempDirectory) } catch let error as NSError { print(error) } } } func createTempDirectory(directoryName: String) -> URL? { let tempDirectoryUrl = URL(fileURLWithPath: NSTemporaryDirectory()) let toBeCreatedDirectoryUrl = tempDirectoryUrl.appendingPathComponent(directoryName, isDirectory: true) if !FileManager.default.fileExists(atPath: URL(string: toBeCreatedDirectoryUrl.absoluteString)!.path) { do{ try FileManager.default.createDirectory(at: toBeCreatedDirectoryUrl, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { print(error) return nil } } return toBeCreatedDirectoryUrl } @IBAction func buttonPressed(_ sender: UIButton){ let scnFolderName = "SCN" let scnFileName = "3D" deleteTempDirectory(directoryName: scnFolderName) guard let scnDirectoryUrl = createTempDirectory(directoryName: scnFolderName) else {return} let scnFileUrl = scnDirectoryUrl.appendingPathComponent(scnFileName).appendingPathExtension("scn") guard let usdzScene else {return} let result = usdzScene.write(to: scnFileUrl, options: nil, delegate: nil, progressHandler: nil) if (result) { print("exporting process is success.") } else { print("exporting process is failed.") } } override func viewDidLoad() { super.viewDidLoad() let usdzUrl: URL? = Bundle.main.url(forResource: "toy_drummer_idle", withExtension: "usdz") guard let usdzUrl else {return} do { usdzScene = try SCNScene(url: usdzUrl) } catch let error as NSError { print(error) } guard let usdzScene else {return} scnView = SCNView(frame: .zero) guard let scnView else {return} scnView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(scnView) self.view.addSubview(exportButton) NSLayoutConstraint.activate([ scnView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), scnView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), scnView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), scnView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30), exportButton.widthAnchor.constraint(equalToConstant: 200), exportButton.heightAnchor.constraint(equalToConstant: 40), exportButton.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), exportButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), ]) DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {[weak self] in guard let self else {return} loadModel(scene: usdzScene) } } func loadModel(scene: SCNScene){ guard let scnView else {return} scnView.autoenablesDefaultLighting = true scnView.scene = scene scnView.allowsCameraControl = true } } ![]("https://developer.apple.com/forums/content/attachment/5ff0197b-7e0b-4efe-b295-cc205c73dc02" "title=Screenshot 2024-06-20 at 12.23.40.png;width=1712;height=1013")
0
0
98
5d