Construct and manage graphical, event-driven user interfaces for iOS or tvOS apps using UIKit.

Posts under UIKit tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

UIDocumentPickerViewController
I'm upgrading my app from minVersion iOS 11 to iOS 12. My compiler says that UIDocumentMenuViewController with UIDocumentPickerViewController is deprecated, they recommend to use directly the last one. So I change the code. fileprivate func openDocumentPicker() { let documentPicker = UIDocumentPickerViewController( documentTypes: [ "com.adobe.pdf", "org.openxmlformats.wordprocessingml.document", // DOCX "com.microsoft.word.doc" // DOC ], in: .import ) documentPicker.delegate = self view.window?.rootViewController?.present(documentPicker, animated: true, completion: nil) } When I open the picker in iOS 17.2 simulator and under it is well shown, like a page sheet. But in iOS 18.0 and up at first it opens like a page sheet with no content but then it is displayed as a transparent window with no content. Is there any issue with this component and iOS 18? If I open the picker through UIDocumentMenuViewControllerDelegate in an iphone with iOS 18.2 it is well shown. Image in iOS 18.2 with the snippet The same snippet in iOS 17.2 (and expected in older ones)
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
271
Jan ’25
Bidirectional Text Rendering Issue in Swift UILabel for Arabic
I'm encountering an issue displaying a large HTML string (over 11470 characters) in a UILabel. Specifically, the Arabic text within the string is rendering left-to-right instead of the correct right-to-left direction. I've provided a truncated version of the HTML string and the relevant code snippet below. I've tried setting the UILabel's text alignment to right, but this didn't resolve the issue. Could you please advise on how to resolve this bidirectional text rendering problem? The results of the correct and incorrect approaches are shown in the image below. Here's the relevant Swift code: let labelView: UILabel = { let label = UILabel() label.textAlignment = .right label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 label.semanticContentAttribute = .forceRightToLeft label.backgroundColor = .white label.lineBreakMode = .byWordWrapping return label }() //Important!! //It must exceed 11470 characters. let htmlString = """ <p style=\"text-align: center;\"><strong>İSTİÂZE</strong></p> <p>Nahl sûresindeki:</p> <p dir="rtl" lang="ar"> فَاِذَا قَرَاْتَ الْقُرْاٰنَ فَاسْتَعِذْ بِاللّٰهِ مِنَ الشَّيْطَانِ الرَّج۪يمِ </p> <p><strong>“</strong><strong>Kur’an okuyacağın zaman kovulmuş şeytandan hemen Allah’a sığın!</strong><strong>”</strong> (Nahl 16/98) emri gereğince Kur’ân-ı Kerîm okumaya başlarken:</p> <p dir="rtl" lang="ar">اَعُوذُ بِاللّٰهِ مِنَ الشَّيْطَانِ الرَّج۪يمِ</p> <p><em>“Kovulmuş şeytandan Allah’a sığınırım” </em>deriz. Bu sözü söylemeye “istiâze<em>” denilir. “Eûzü”</em>, sığınırım, emân dilerim, yardım taleb ederim, gibi anlamlara gelir. It must exceed 11470 characters.</p> “”” if let data = htmlString.data(using: .utf8) { let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ] do { let attributedString = try NSAttributedString(data: data, options: options, documentAttributes: nil) labelView.attributedText = attributedString } catch { print("HTML string işlenirken hata oluştu: \(error)") } } I'm using iOS 18.2 and Swift 6. Any suggestions on how to correct the bidirectional text rendering?
0
0
311
Jan ’25
UIViews resized to 540x600
I have a project that has many dialogue boxes that pop up. The method I've chosen (and worked well for years) is to put a UIView on a ViewController with a slightly opaque background. Dialogue info is in the UIView. With the upgrade to Xcode 16 and iOS 18 all of my UIViews in my project have been re-sized to 540x600 and I can't figure out how to change them back to their original size. Many of them are now unusable as the information they previously contained was much larger than that. Any idea who to blame (Xcode 16 or iOS 18?) or how to fix it? I'm desperate enough I'm willing to use code level support but it requires a small test project and the issue is with a large existing project. Can't reproduce it on a new project.
Topic: UI Frameworks SubTopic: UIKit Tags:
3
0
198
Jan ’25
SwiftUIKit Got double back button and blank screen
I tried to update my ios from 17.2 to 18.1 on my iphone 14 pro. I use this device for testing my apps. when i go to my sdk, i got double back button and when i clicked the back button it will go to blank screen here is the ss double back button got blank screen its never happened on ios 17 and below i use coordinator and UINavigationController anyone have solutions?
1
0
259
Jan ’25
iPadOS18 UITabBarController not releasing viewControllers after deinit with sidebar enabled
In iPadOS18 UITabBarController not releasing viewControllers after deinit with sidebar enabled. On checking the memory Graph Debugger we could see that the viewControllers are hold by UITab which in turn hold by UITabSidebarItem. We don't have control over the UITabSidebarItem and unable to remove the reference. The issue not happens when tabbarController mode is set to 'tabBar' instead of 'sidebar'. We have event tried to set empty tabs before dismiss the view but still the original tabs are not removing in memory and holding the viewcontollers as well. Anyone assist on this issue. Sharing the sample code here
1
0
394
Jan ’25
iOS Widget can't connect to the host app and shows Skeleton.
Some of our users keep reporting that occasionally some widgets (which initially were working perfectly) are now broken and show only skeletons. Note that the app has multiple widgets, and this happens only to some of them (that is when some widgets get broken, some other widgets are still working normally). While developing the app, I came across this symptom as well, and when I read the device console, I found the following errors in the console (which the system was repeatedly reporting to the console): Unable to get connection interface: Error Domain=LNConnectionErrorDomain Code=1100 "Unable to locate com.example.app.MyAppntents for the com.apple.intents-service extension point" UserInfo={NSLocalizedDescription=Unable to locate com.example.app.MyAppIntents for the com.apple.intents-service extension point} The affected widgets use the 'UserDefaults with groups' to read the data that is stored by the host app. And I think that sometimes the widget fails (or even crashes) while reading the data from the UserDefaults and it ends up showing the skeleton. The only remedy I found was Uninstall the app Reboot the device Install the app again. After this, the widget starts to work again.. So, what can be the reason behind this? Is this an iOS bug or what and how to fight it?
2
0
325
Jan ’25
Mac Catalyst SwiftUI – . focused() not working
Hello, given this following simple SwiftUI setup: struct ContentView: View { var body: some View { CustomFocusView() } } struct CustomFocusView: View { @FocusState private var isFocused: Bool var body: some View { color .frame(width: 128, height: 128) .focusable(true) .focused($isFocused) .onTapGesture { isFocused.toggle() } .onKeyPress("a") { print("A pressed") return .handled } } var color: Color { isFocused ? .blue : .red } } If I run this via Mac – Designed for iPad, the CustomFocusView toggles focus as expected and cycles through red and blue. Now if I run this same exact code via Mac Catalyst absolutely nothing happens and so far I wasn't able to ever get this view to accept focused state. Is this expected? I would appreciate if anyone could hint me on how to get this working. Thank and best regards!
5
0
494
Apr ’25
Populating Now Playing with Objective-C
Hello. I am attempting to display the music inside of my app in Now Playing. I've tried a few different methods and keep running into unknown issues. I'm new to Objective-C and Apple development so I'm at a loss of how to continue. Currently, I have an external call to viewDidLoad upon initialization. Then, when I'm ready to play the music, I call playMusic. I have it hardcoded to play an mp3 called "1". I believe I have all the signing set up as the music plays after I exit the app. However, there is nothing in Now Playing. There are no errors or issues that I can see while the app is running. This is the only file I have in Xcode relating to this feature. Please let me know where I'm going wrong or if there is another object I need to use! #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import <MediaPlayer/MediaPlayer.h> #import <AVFoundation/AVFoundation.h> @interface ViewController : UIViewController <AVAudioPlayerDelegate> @property (nonatomic, strong) AVPlayer *player; @property (nonatomic, strong) MPRemoteCommandCenter *commandCenter; @property (nonatomic, strong) MPMusicPlayerController *controller; @property (nonatomic, strong) MPNowPlayingSession *nowPlayingSession; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"viewDidLoad started."); [self setupAudioSession]; [self initializePlayer]; [self createNowPlayingSession]; [self configureNowPlayingInfo]; NSLog(@"viewDidLoad completed."); } - (void)setupAudioSession { AVAudioSession *audioSession = [AVAudioSession sharedInstance]; NSError *setCategoryError = nil; if (![audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError]) { NSLog(@"Error setting category: %@", [setCategoryError localizedDescription]); } else { NSLog(@"Audio session category set."); } NSError *activationError = nil; if (![audioSession setActive:YES error:&activationError]) { NSLog(@"Error activating audio session: %@", [activationError localizedDescription]); } else { NSLog(@"Audio session activated."); } } - (void)initializePlayer { NSString *soundFilePath = [NSString stringWithFormat:@"%@/base/game/%@",[[NSBundle mainBundle] resourcePath], @"bgm/1.mp3"]; if (!soundFilePath) { NSLog(@"Audio file not found."); return; } NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath]; self.player = [AVPlayer playerWithURL:soundFileURL]; NSLog(@"Player initialized with URL: %@", soundFileURL); } - (void)createNowPlayingSession { self.nowPlayingSession = [[MPNowPlayingSession alloc] initWithPlayers:@[self.player]]; NSLog(@"Now Playing Session created with players: %@", self.nowPlayingSession.players); } - (void)configureNowPlayingInfo { MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter]; CMTime duration = self.player.currentItem.duration; Float64 durationSeconds = CMTimeGetSeconds(duration); CMTime currentTime = self.player.currentTime; Float64 currentTimeSeconds = CMTimeGetSeconds(currentTime); NSDictionary *nowPlayingInfo = @{ MPMediaItemPropertyTitle: @"Example Title", MPMediaItemPropertyArtist: @"Example Artist", MPMediaItemPropertyPlaybackDuration: @(durationSeconds), MPNowPlayingInfoPropertyElapsedPlaybackTime: @(currentTimeSeconds), MPNowPlayingInfoPropertyPlaybackRate: @(self.player.rate) }; infoCenter.nowPlayingInfo = nowPlayingInfo; NSLog(@"Now Playing info configured: %@", nowPlayingInfo); } - (void)playMusic { [self.player play]; [self createNowPlayingSession]; [self configureNowPlayingInfo]; } - (void)pauseMusic { [self.player pause]; [self configureNowPlayingInfo]; } @end
2
0
502
Feb ’25
SwiftUI Manual Orientation Control for Views - Solution and a Bug!
I am working on a project that contains a QuickLook View and Some ARViews. I want to restrict the entire app to Portrait orientation, but I want to allow the ARView to have Portrait and Landscape orientation. If I restrict the app to Portrait in the Deployment Info settings, we can still turn the device to landscape in the ARView, However, there is an issue with "some" spatial audio files within the digital experience. Some spatial audio items, are placed appropriately, and others are panned oddly left. If we allow Landscape Left and Right in the Deployment Info settings, all spatial audio behaves appropriately. So, we need to "lock" every other view as Portrait and only allow Portrait and Landscape on the ARView. I'm not smart enough to know how to do that, but I found this excellent package on GitHub. It works as expected. https://github.com/wvteijlingen/swiftui-interface-orientation However! When we wrap SwiftUI with UIKit, it appears every single view that contains an ARView is initialized at launch even though it is not visible. So, when the app launches, it is running multiple ARViews at once. It appears we need to have some kind of lazy loading, so this doesn't occur, but again, I am not knowledgable enough for this yet. I tried to wrap it all in a LazyVStack, I tried a LazyView struct, but I couldn't get it to build appropriately. I feel like this might be a common thing, so maybe there's already a simple answer I'm not able to locate? Any ideas??
1
0
415
Jan ’25
INUIHostedViewControlling ViewController's Life Cycle Events not being Called
I am implementing a new Intents UI Extension and am noticing that the viewWillDisappear, viewDidDisappear, and deinit methods are not being called on my UIViewController that implements INUIHostedViewControlling, when pressing the "Done" button and dismissing the UIViewController. This causes the memory for the UI Extension to slowly increase each time I re-run the UI Extension until it reaches the 120MB limit and crashes. Any ideas as to what's going on here and how to solve this issue?
2
0
378
Jan ’25
Programmatically setting accessibility focus broken?
Hello! I'm trying to improve the accessibility of a UIKit login form in our iOS app. If an error occurs, an error message is shown in a label that is hidden by default. For our VoiceOver users, I want to move the focus to the error message label so that VoiceOver reads out the error message. I'm trying to achieve this using UIAccessibility.post, but try as I might, it does not work. To better understand the problem, I created a very simple App which shows a button and a label (always visible), and on pressing the button, I post an accessibility notification: UIAccessibility.post(notification: .layoutChanged, argument: label) What I expect to happen is for the focus to move from the button to the label. What happens instead is the focus stays with the button and VoiceOver reads out the button's label again. So it seems to process the notification, but ignore the argument. Am I misunderstanding how accessibility notifications work or is this simply broken at the moment? I am testing this withy my iPhone with the current iOS version 18.2.1 By the way, using the more modern variant leads to the same result: AccessibilityNotification.LayoutChanged(label).post()
3
0
467
Jan ’25
Non-sendable type AVMediaSelectionGroup
Hi all, we try migrate project to Swift 6 Project use AVPlayer in MainActor Selection audio and subtitiles not work Task { @MainActor in let group = try await item.asset.loadMediaSelectionGroup(for: AVMediaCharacteristic.audible) get error: Non-sendable type 'AVMediaSelectionGroup?' returned by implicitly asynchronous call to nonisolated function cannot cross actor boundary and second example `if #available(iOS 15.0, *) { player?.currentItem?.asset.loadMediaSelectionGroup(for: AVMediaCharacteristic.audible, completionHandler: { group, error in if error != nil { return } if let groupWrp = group { DispatchQueue.main.async { self.setupAudio(groupWrp, audio: audioLang) } } }) }` get error: Sending 'groupWrp' risks causing data races
1
0
449
Feb ’25
iPadOS 18 App (on Apple Silicon) - Duplicate Tab Bar Appearing in Toolbar
With iPadOS 18, the UITabBar now defaults to the floating style. I successfully reverted the tab bar to its traditional style by overriding the UITabBarController's horizontalSizeClass property: self.tabBarController?.traitOverrides.horizontalSizeClass = .unspecified When I launch the app on my Mac using Apple Silicon, TWO tab bars appear: One appears at the bottom of the screen, like a traditional tab bar. The second tab bar is still embedded in the app toolbar in its floating style. Is this a bug? How do you ensure that overriding the horizontalSizeClass will remove/hide the floating tab bar when running an app on Apple Silicon? TIA! (Demonstrated on a test project)
0
0
362
Jan ’25
How to determine the default duration of a long-press
Using gesture recognizers it is easy to implement a long-press gesture to open a menu, show a preview or something else on the iOS platform. And you can provide the duration the user must hold down the finger until the gesture recognizer fires. But I could not yet find out how to determine the default duration for a long-press gesture that is configured in the system settings within the "accessibility" settings under "Haptic Touch" (the available options are fast, standard and slow here). Is it possible to read out this setting, so my App can adapt to this system setting as well?
1
0
296
Jan ’25
State Restoration not restoring root view controller
I'm trying to implement UI state restoration in an old Objective-C UIKit app that does not use scenes and also does not have a storyboard. I have implemented the correct AppDelegate methods -- application:shouldSaveSecureApplicationState: and application:shouldRestoreSecureApplicationState: -- and I can see that they are being called when expected. I have also implemented the state restoration and UIViewControllerRestoration viewControllerWithRestorationIdentifierPath:coder: methods for the view controllers I want to persist and restore; along with correctly setting their restorationIdentifier and restorationClass properties. I can also see that those are being called when expected. I've also installed the restorationArchiveTool and have verified that the persisted archive contains the expected view controllers and state. However, once state restoration is complete, the window's rootViewController property is still nil and has not been assigned to the view controller that has the restorationIdentifier of the rootViewController at the time the state is persisted. I found this sample app that does what I want to do -- persist and restore the state of the view controllers without the use of storyboards. Running that I verified that it does in fact work as expected. https://github.com/darrarski/iOS-State-Restoration The difference between what that app does and what mine does, is that it always creates the top level view controllers in application:willFinishLaunchingWithOptions:. func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { let viewControllerA = DemoViewController() viewControllerA.title = "A" let navigationControllerA = UINavigationController(rootViewController: viewControllerA) navigationControllerA.restorationIdentifier = "Navigation" let viewControllerB = DemoViewController() viewControllerB.title = "B" let navigationControllerB = UINavigationController(rootViewController: viewControllerB) navigationControllerB.restorationIdentifier = "Navigation" let tabBarController = UITabBarController() tabBarController.restorationIdentifier = "MainTabBar" tabBarController.viewControllers = [navigationControllerA, navigationControllerB] window = UIWindow(frame: UIScreen.main.bounds) window?.restorationIdentifier = "MainWindow" window?.rootViewController = tabBarController return true } Unfortunately, my app is more dynamic and the rootViewController is determined after launch. When I updated the app to be structured more like mine, I see that it fails the same as mine and no longer restores the rootViewController. class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var didRestoreState = false func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.restorationIdentifier = "MainWindow" return true } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { if !didRestoreState { let viewControllerA = DemoViewController() viewControllerA.title = "A" let navigationControllerA = UINavigationController(rootViewController: viewControllerA) navigationControllerA.restorationIdentifier = "Navigation" let viewControllerB = DemoViewController() viewControllerB.title = "B" let navigationControllerB = UINavigationController(rootViewController: viewControllerB) navigationControllerB.restorationIdentifier = "Navigation" let tabBarController = UITabBarController() tabBarController.restorationIdentifier = "MainTabBar" tabBarController.viewControllers = [navigationControllerA, navigationControllerB] window?.rootViewController = tabBarController } window?.makeKeyAndVisible() return true } func application(_ application: UIApplication, shouldSaveSecureApplicationState coder: NSCoder) -> Bool { let libraryDirectory = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first let appStateUrl = libraryDirectory?.appendingPathComponent("Saved Application State") NSLog("Restoration files: \(appStateUrl?.path ?? "none")") return true } func application(_ application: UIApplication, shouldRestoreSecureApplicationState coder: NSCoder) -> Bool { return true } func application(_ application: UIApplication, didDecodeRestorableStateWith coder: NSCoder) { didRestoreState = true } } I don't really understand why this doesn't work since the archive file looks identical in both cases, and the methods used to create and restore state of the view controllers are being called in both cases. Is there something else I need to do to correctly restore the view controllers without having to create them all before state restoration begins?
2
1
297
Jan ’25
Unexpected Insertion of U+2004 (Space) When Using UITextView with Pinyin Input on iOS 18
I encountered an issue with UITextView on iOS 18 where, when typing Pinyin, extra Unicode characters such as U+2004 are inserted unexpectedly. This occurs when using a Chinese input method. Steps to Reproduce: 1. Set up a UITextView with a standard delegate implementation. 2. Use a Pinyin input method to type the character “ㄨ”. 3. Observe that after the character “ㄨ” is typed, extra spaces (U+2004) are inserted automatically between the characters. Code Example: class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } extension ViewController: UITextViewDelegate { func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { print("shouldChangeTextIn: range \(range)") print("shouldChangeTextIn: replacementText \(text)") return true } func textViewDidChange(_ textView: UITextView) { let currentText = textView.text ?? "" let unicodeValues = currentText.unicodeScalars.map { String(format: "U+%04X", $0.value) }.joined(separator: " ") print("textViewDidChange: textView.text: \(currentText)") print("textViewDidChange: Unicode Scalars: \(unicodeValues)") } } Output: shouldChangeTextIn: range {0, 0} shouldChangeTextIn: replacementText ㄨ textViewDidChange: textView.text: ㄨ textViewDidChange: Unicode Scalars: U+3128 ------------------------ shouldChangeTextIn: range {1, 0} shouldChangeTextIn: replacementText ㄨ textViewDidChange: textView.text: ㄨ ㄨ textViewDidChange: Unicode Scalars: U+3128 U+2004 U+3128 ------------------------ shouldChangeTextIn: range {3, 0} shouldChangeTextIn: replacementText ㄨ textViewDidChange: textView.text: ㄨ ㄨ ㄨ textViewDidChange: Unicode Scalars: U+3128 U+2004 U+3128 U+2004 U+3128 This issue may affect text processing, especially in cases where precise text manipulation is required, such as calculating ranges in shouldChangeTextIn.
5
0
956
Jan ’25
Troubles with CFBundleDocumentTypes and photos
I'm working on adding CFBundleDocumentTypes to my Info.plist so that a user can share an image from other apps on their device and have it open inside my iPhone app. I seem to be able to get this to work for sharing a single photo from the Photos app, but not for (1) multiple photos from the Photos app or (2) images from Safari. One thing that makes this difficult is that my changes to Info.plist sometimes have no effect. I can remove CFBundleDocumentTypes and still see the icon, for example. Or I can add a new accepted UTI, but it has no effect. I've tried cleaning and rebuilding, deleting and reinstalling the app...no success. I tried in the simulator, too, and even Erase Content and Settings didn't force changes to be applied. I'm not sure what else to try here. Anyway, I'd like my app to appear in the Share sheet for photo(s) from the Photos app, Mail and Safari, in particular, but really from any app that supports sharing photos. I can share the config that seemed to work, but since changing it doesn't always have an effect, I can't guarantee that this was the one that worked. At the moment, it doesn't work, but I'm not sure why. Here it is: &lt;key&gt;CFBundleDocumentTypes&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;CFBundleTypeIconFiles&lt;/key&gt; &lt;array/&gt; &lt;key&gt;CFBundleTypeName&lt;/key&gt; &lt;string&gt;Image&lt;/string&gt; &lt;key&gt;CFBundleTypeRole&lt;/key&gt; &lt;string&gt;Viewer&lt;/string&gt; &lt;key&gt;LSHandlerRank&lt;/key&gt; &lt;string&gt;Alternate&lt;/string&gt; &lt;key&gt;LSItemContentTypes&lt;/key&gt; &lt;array&gt; &lt;string&gt;public.data&lt;/string&gt; &lt;string&gt;public.jpeg&lt;/string&gt; &lt;string&gt;public.png&lt;/string&gt; &lt;string&gt;public.image&lt;/string&gt; &lt;string&gt;public.gif&lt;/string&gt; &lt;string&gt;public.url&lt;/string&gt; &lt;string&gt;public.content&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/array&gt; &lt;key&gt;LSSupportsOpeningDocumentsInPlace&lt;/key&gt; &lt;true/&gt; In my code, I also defined the following method in my SceneDelegate (though I think the problem is just with Info.plist): func scene(_ scene: UIScene, openURLContexts URLContexts: Set&lt;UIOpenURLContext&gt;) { Here are my questions: How do I make sure that my changes to Info.plist apply? Is there a cache somewhere that I have to force to clear? This is the trickiest part of this, because I can't reliably try an experiment and see if it worked. Adding the specific image UTI’s (public.jpeg, public.png) seemed to help, even though those types should conform to public.image, which conforms to public.data and public.content. Is it actually necessary to specify those? If the user selects multiple photos in the Photos app, my app doesn’t appear, but other third-party apps on my phone do. How can I support multiple photos? This configuration doesn't reliably show my app for Safari images - what do I need to do to make that happen? I had to use “public.data” when I briefly had Safari sharing working, but there doesn't seem to be a way to get a UTI from UIOpenURLContext. Right now, my code just tries to load the data as an image and aborts if UIImage(data:) returns nil. Is this a safe way of doing this? Is there a way to get the UTI for the data?
2
0
601
Jan ’25
Validate drag operations with Transferable
Let's say I want to build a simple photo management app on Mac or iPad with Swift UI. This app has multi-window support. My photos are organized inside albums. I should be able to drag photos between windows from one album to another. I struggle to get this working properly with Swift UI. Writing modern code I would like to use Transferable. Let's say my photos are not real files. So I can't use a FileRepresentation. Instead I use CodableRepresentation and encode an identifier. This identifier is later used to drive the move operation between folders. I ran into some limitations here Transferable seems to be meant for copy-like Drag & Drop operations. I have no possible to get a "move" cursor on macOS (it's always the copy cursor with the green + sign). Also the API reads like it is about importing/exporting – not moving. When using dropDestination on ForEach, I completely lack the possibility to deny a drop (e.g. when a photo is already part of the album). I'd like to have modifier key to switch between copying and moving. Sometimes a drop should be redirected to a different index. How to do that? Is there any chance to do this with Transferable? It even doesn't seem to be easy with NSItemProvider and onDrop/onDrag? Or should we still use a plain old UICollectionView/NSCollectionView, if we want to have more sophisticated control over drag/drop validation?
4
0
378
Jan ’25