Prevent or clear app state persistence for MacOS SwiftUI Document Based App - macos

I am developing a MacOS Document based app using SwitfUI on MacOS 12.0.1 using Xcode 13.1 on a MacbookPro M1 Pro. I am encountering an issue that the app is always re-opening the document browser at the last used directory. Which is OK when it is on the Machine but a pain if the last used was on a network drive. I am trying to find a way of suppressing this "always restore using the last directory" mode of operation.
I have tried using the #NSApplicationDelegateAdaptor approach and implementing;
func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
print(#function + " returning false")
return false
}
within my NSApplicationDelegate class, which does get called (although it seems sometimes after the dialog is presented), however this does not stop the app secretly remembering the last directory.
Does any know where this information might be being hidden or if it can be suppressed ?
I have looked for, but cannot find, a way of injecting a starting directory into a DocumentGroup as a possible solution.
TIA Alan.

Ok, for anyone who ends up here looking for a similar issue.
After a chunk of digging I found the answer, for me, was to add
UserDefaults.standard.removeObject(forKey: "NSNavLastRootDirectory")
into the app startup. It was also suggested to do
UserDefaults.standard.removeObject(forKey: "NSNavLastCurrentDirectory")
However, just doing the first appears to suppress the file open dialog, doing both causes the file open dialog to open with the user Documents directory.

Related

SwiftUI / Xcode Error - Updating took more than 5 seconds

When I try to preview one of my views in the canvas I keep getting the following error:
PreviewUpdateTimedOutError: Updating took more than 5 seconds
All my other views load perfectly fine.
Why is this happening and how do I resolve?
I am using SwiftUI in Xcode 11.4 (public release)
I stopped using the simulator and chose "Any iOS Device" and that solved the problem.
In my case the issue was this line in Build settings:
Something I did accidentally changed signing settings in my project. Specifically, "signing identity" was set to "Sign to Run Locally.".
For some reasons, SwiftUI Previews don't work then.
Simply deleting this line from build settings (aka setting default value) solved the problem.
Some time, the error displaying is not the real error.
For me it was because i missing : .environmentObject(...)
As of Xcode 12.5.1, the message PreviewUpdateTimedOutError: Updating took more than 5 seconds most likely means that your app crashed and thus updating the preview failed. The real reason for the crash is unfortunately obscured by this useless message (why Apple would do that is beyond me). To get at the real reason, you'll need to:
click Diagnostics at the top of the preview next to the useless error message
in the next dialog, click Generate Report > Reveal in Finder
This will take a bit. Then Finder will open with a folder highlighted. Open that folder. Inside you'll see a lot of log files and folders.
If your app indeed crashed, you'll see a folder called CrashLogs which contains crash logs for your app, including the error message and stack trace. This should help you resolve the actual error causing the preview to break.
Note that for me, sometimes the CrashLogs were not included in the report even though my app really did crash. Retrying the preview and generating another report fixed this for me. The whole error reporting process seems to be rather unstable for the previews, unfortunately.
Try Clean (Shift + ⌘ + K) and Build (⌘ + B) to build again the SwiftUI project, it works in Xcode 11.6. Try building a basic hello world app.
In my case the issue was that the PreviewProvider was marked private. Simply make it internal or remove the private access modifier.
private /* <- remove */ struct YourView_Previews: PreviewProvider {
static var previews: some View {
// Your previews
}
}
I am using Version 13.2.1 (13C100). I have Clean (Shift + ⌘ + K) and Build (⌘ + B) the project. But, the problem remains.
Then, just restarted Xcode. And the problem gone.
In my case viewModel required to display SwiftUI_preview was doing a call to a CoreData (fast call) in the init of the viewModel.
Moved actual call of that "reload() method" so it's not called on preview, fixed.
(I believe the correct way is to use mocked protocol instead of instance of the viewModel)
If you have an .onAppear clause, try commenting that out for preview.
None of these suggestions helped me but I did discover that you can't rely entirely on a successful build to pick up all issues. In my case I had '.modifier(modifier:)' entered incorrectly as 'modifier(modifier:)'. My code built successfully but my preview did not work until I added the period before modifier.
For me the issue was related to a force unwrapping of an element not being found at preview time.
Note: Always check the diagnostics report. The issue will be at the top section after termination reason.
In my case the canvas/screen size was smaller than the content, so simply wrapping my content in the scrollView do remove the error and displaying the content in the canvas.
I had a fatalError("...") in my code, which I only figured out after reading the diagnostic logs. Would be nice if SwiftUI actually hinted this!
You can get the diagnostics by clicking "Diagnostics" next to "Try Again" at the top of the preview window.
To summarise lots of answers here, it seems that the preview taking a while to update is the equivalent of a crash, when running on a real device or on the simulator.
First comment out all the environment Objects are used for the particular View. Once you get preview then uncomment it to run the build. This trick works for me
//#EnvironmentObject var observerObj:PropertyObserver
I had this issue as well, and nothing fixed the problem. I am now on 11.6 and after updating the issue went away. I think it might be a problem with Xcode 11.4.
I'd suggest updating Xcode if possible.
In SwiftUI, you couldn't add more than 10 subviews into your contentview, otherwise it couldn't compile.
I had the same problem, then I started to comment out the subViews inside my main view, one by one & try to preview again then I found out the problem was caused because I forgot to put a dot before one of the subViews attributes.
So that's how I fixed it.
The reason is because its unable to find the landmarkData.json file. To resolve this,
select landmark.json file in Resources.
Show Inspectors ( top right icon )
Select show file inspector
Under Target membership, select / check Landmarks
This should resolve the preview issue.
For some reason, in SwiftUI, when I embeded Text in Scroll View and VStack, this error occurred. After few unsuccessful attempts to fix this by clearing and building project, I deleted code and wrote it down again, same as it was. Now it is working.
I had my run device set to a real device I use for testing. When I changed that to one in the simulator it started working again.
Similar to #YannSteph, this happened to me because I put the .environmentObject() at the app entry point where it creates the first view:
#main
struct RecipeApp: App {
var body: some Scene {
WindowGroup {
RecipeTabView()
.environmentObject(RecipeModel())
}
}
}
But this prevented the preview from working. I thought I was being smart putting it there, so all the views could have access to it, but it just crashed the preview.
Moving it back into the main View.Swift file that is my app's starting view fixed the preview issue.
^^^
EDIT: Ran into this again when I didn't put the .environmentObject() in the struct for the preview. Probably a rookie mistake but there appears to be many ways to trigger this error.
I had the same issue after creating a brand new Multiplatform App project using Xcode 12.5. Based on the solutions above I followed a hunch and now believe that the issue is due to invalid path parameters.
After renaming the Schemes and Targets from (iOS) to .iOS (and the same for macOS), to remove spaces and brackets, it is now working.
I had this issue after changing bundle id and signing from personal to team.
After changing device to Any device as advised here, I received another error description, saying
Could not install the preview host "AppName.app" on iPhone 12 Pro Max
agentBundle = com.bundle.Its.AppName {
url: file:///Users/macbookair/Library/Developer/Xcode/DerivedData/AppName-> desupjbpqvjlegfbskxydixpouvc/Build/Intermediates.noindex/Previews/AppName/Prod> ucts/Debug-iphonesimulator/AppName.app
> version: 49557
signingInformation: Code Signing {
identifier: com.bundle.AppName
hasGetTaskAllow: false
isSandboxed: false
}
}
Clean build, deleting Derived, Deleting all apps installed on simulators, cleaning Xcode Cache, restarting Xcode and Mac didn't help.
What had helped was creating new project with initially correct bundle id and copying all my files there.
I have got into the same issue on Xcode 12.4, but the code works fine on Xcode 13.0.
I was following the IOS App Dev Tutorial, where one creates an app named ScrumDinger. I ran into this issue at Displaying Data in List
In my case the problem was that I wrote in CardView.swift
HStack {
Label("\(scrum.attendees.count)", systemImage: "person.3")
accessibilityLabel("\(scrum.attendees.count) attendees")
instead of
HStack {
Label("\(scrum.attendees.count)", systemImage: "person.3")
.accessibilityLabel("\(scrum.attendees.count) attendees")
The missing dot before accessibilityLabel was the problem.
Tutorial:
https://developer.apple.com/tutorials/app-dev-training/displaying-data-in-a-list
In my case the issue was that I was trying to preview a view with a fixed width (.previewLayout(.fixed(width: 344, height: 220))) wider than the selected simulator (iPhone SE 1st generation) 😬
I get this error often. My last time of occurrence, I had "gesture" instead of ".gesture". Usually its best to just need to find the error in your code yourself because Xcode does not point out the issue directly.
I only had Xcode 14 Beta installed on my machine and the previews did not work. All of the other answers did not work for me.
Installing Xcode 13.4.1 and running the preview with it did solve my problems and now I can also see the preview in Xcode 14 Beta as well.
In my case, I disabled automatic canvas refresh by going to Editor -> Canvas -> Automatically Refresh Canvas and making sure it.
Then I use ⌥⌘P (Command-Option-P) to refresh the canvas preview.

Cocos desktop app can not access to files on MacOS

I have an application with the following structure:
./Data/test.txt
./TestMacOSApp
So my TestMacOSApp opens ./Data/test.txt and uses the content of test.txt. This app was working for a long time either on my MacBook or others MacBook. Recently I noticed that the app works on my MacBook fine,
but on others it crashes throwing "File is not found exception".
I create TestMacOSApp using XCode v9.1.
MacOS version is 10.12.6.
The App creation steps are Archive->Export->ExportApp (Without re-signing).
Does someone else have such an issue?
How can I solve this issue?
I don't know how you open the file because you didn't provide the code which does this.
But I know that, when you export your app on other computers, it is important to calculate the real path with fullPathForFilename, instead of giving directly the path that you know. Like this:
auto fileUtils = FileUtils::getInstance();
string content = fileUtils->getStringFromFile(fileUtils->fullPathForFilename(filename));
Have you done this? If you have, and it doesn't work, your file is probably just not where you expect it to be, so please check again.

QLPreviewView can not show the quicklook preview in sandbox

I use QLPreviewView to show the quicklook preview in the app. Without sandbox, this works well, but once change the app to sandbox, the preview can not show up.
I found the error in Console: QuickLookUIHelpe(20786) deny file-read-data XXX.
I have used the security-scoped bookmarks & com.apple.security.files.user-selected.read-write to grant access the user home dir, then:
[allowedURL startAccessingSecurityScopedResource];
self.myPreiviewItem.myURL = fileURL;
self.myQLPreviewView.previewItem = self.myPreiviewItem;
[self.myQLPreviewView refreshPreviewItem];
[allowedURL stopAccessingSecurityScopedResource];
with these, I can delete files of user home dir, but the QLPreviewView can not work.
I do not know what is the difference between these 2 scenes, does QLPreviewView need more for sandbox?
If I add com.apple.security.files.downloads.read-only into the entitlement, the files in "Downloads" can be previewed, but other files of user home dir can not be previewed.
Finally I have found the solution!
refreshPreviewItem is an async call, so before Mac finishes loading the preview, the following api stopAccessingSecurityScopedResource immediately shutdown the access, as a result, Mac failed to load the preview successfully.
so the solution is: do NOT call stopAccessingSecurityScopedResource here, keep the allowedURL's access right until you do not need the QL preview function, and then call stopAccessingSecurityScopedResource there, such as when closing the window.
I encountered this, or at least a similar, issue a while back (in Mavericks).
This is why I started asking users for access to parent folders of files they wish to Quick Look. Feel free to look at how I do it in this app of mine, version 1.1 at the time of this writing. Just go into Chikoo → Preferences… → Folder Access. Here are two screenshots:
I confess that this is not a great solution. It’s a compromise that I came up with to work around the problem.

Using OSX Security-Scoped Bookmarks in a Firemonkey app

I have been developing an OSX app with Delphi XE3 and running into various problems. The latest one is with the sanboxed version built for the Apple Appstore.
The user has to select an arbitrary folder and the app needs to get access to it. Since there is a problem with the OpenDialog, I had to turn to drag-drop functionality instead.
The user drags a folder to the app, the sandbox gives the app temporary access to it and all works properly.
To preserve the access to this folder when the app is restarted I have to use the so-called "security-scoped bookmarks"
I am having two issues with them:
1) How to add the "com.apple.security.files.bookmarks.app-scope" entitlement to an XE3 firemonkey app? It is not available in the Project Options->Entitlements. If I add it manually in the ".entitlements" file it gets overwritten when the app is built.
So is there a way to add a custom entitlement that is not in the list in the project options?
2) To create the bookmark I should use the NSURL.bookmarkDataWithOptions method. I think it should be used like this, but I am not sure of the exact syntax:
var
URL: NSURL;
Err: NSError;
Data: NSData;
...
URL := TNSURL.Create;
Data := URL.bookmarkDataWithOptions(NSURLBookmarkCreationWithSecurityScope, nil, #Err);
...
Maybe there should be a call to Wrap(...) instead of Create.
I have not yet experimented with it, because it is pointless without the answer to issue 1).
It seems no one has written anything about these problems for Delphi, but I hope someone here has experience with that.
Thanks in advance.
Edit:
For problem 1) I tried to add edit manually the ".entitlements" file in the OSX32 folder and set it to read-only to prevent it from being overwritten. It was too easy to be true of course, because the linker complained that the file can not be modified...
OK, I finally found the way to manually add entitlements that are not available in the Project Options > Entitlements.
Instead of selecting the "App Store" build in the Project Manager you have to select a Normal release build and deploy the application as usual.
The application gets deployed in the PAServer scratch-dir as APP package. Inside this package there is an "Entitlements.plist" file, which is in XML format and can be edited with a text editor. It is quite obvious how to add new entitlements once you open the file.
After it is edited, the app has to be code-signed manually and a package has to be prepared. It is slightly more complicated than using the Delphi IDE, but there are instructions about it on the Embarcadero and Apple websites and it actually went without problems.
Still haven't tried the bookmarkDataWithOptions functions.
An alternative could be to deactivate the checkbox for the entitlements-file in the deployment page.
But attention: Evry time you change between Build/Release or App Store/Normal, delphi activates the checkbox. That means you have to deactivate it again in the deplayment-page, to avoid the transfer of this file to the mac PC.
By the way: Do you have tryed meanwhile the StartAccessingSecurityScopedResource function?
In the MacApi.Foundation unit the function is not declared in the NSURL interface.
Do you have found a way to use this function?

XCode's Documentation Complains "File Not Found" but Gives Correct Results

When I'm searching for something in the Developer Documentation of Xcode, I constantly get "File not Found"/"The requested file was not found in any documentation set."
The odd thing is, it still works. E.g., if I search for NSSound, I can find NSSound.
The error dialogue is invoked whenever it attempts to search as I type, which makes it particularly annoying.
This only happens when I select certain documentation sets (e.g., "iPhone OS 3.1 Library"). I tried deleting it & re-installing, but the same result. (Perhaps I didn't remove everything?)
I put up a post to fix this over here:
http://allens-techlog.blogspot.com/2009/11/fixing-xcode-requested-file-was-not.html
Another fix is to change your searching from "All Doc Sets" to "Apple iPhone OS 3.1". Once you've done that, select the "Apple iPhone OS 3.0" docset. Although it's old you won't get the error and in a month or two you can change it back.
This error is occurring again with Xcode 5+ and Mavericks doc sets. For example:
The requested file cannot be found:
/var/folders/l5/g1r3n28s1v38t5ntjqb_1dq80000gn/T/xcdocui.css.
When it appears try in this order:
Restart Xcode
Log out / log in
Restart
If you don't want to log out or restart, you can delete the temporary parent folder of the CSS file that cannot be found (T stands for 'temporary'), then quit and restart Xcode. But note this will also delete temporary files other running apps might be using, so you might get similar "file cannot be found" messages from other apps, until they are also restarted. Also see this Apple Mailing List post.
I get this problem even in Mavericks and Xcode5, almost 5 years later!
Here's maybe a less scary method than just deleting the rather populated "T" directory:
get out of Xcode. Try not to do anything else either, (who knows what else writes in T?),
but quit Xcode at least.
navigate to the /var/folders/...whatever.../T/.. directory (parent of T)
hide it temporarily with
mv T xT
start up Xcode
look at some doc just to be sure
quit Xcode
look at that same dir; a new T will be there with xcdocui.css in it
cp T/xcdocui.css xT/xcdocui.css
swap it back quickly with rm -rf T ; mv xT T
restart Xcode and see if it works.
"It works for me"
This .css file is kind of small and boring to be causing such a fuss!
That was your early Thanksgiving treat from Apple. They sent a docset 3.1 "update" out about 4-5 days ago and F'ed up alot of peoples documentation. It's basically unusable for me right now...I can't do anything without having do dismiss a never-ending barage of "page not found" error dialogs. It also trashed 50% of the favorites links I had on the left panel of documents. I assume these were from the docsets it now want's me to re-subscribe to but gives an error every time I try.
Haven't seen alot of posts about it yet so I would bet that Apple will likely do nothing. If it were possible to get a human on the phone over there I would have some answers to go along with the frustration.
Happy Thanksgiving
PS. Best to turn OFF the auto-update option in documentation. If not for having that option ON I'd currently be oblivious to this issue and capable of viewing my documentation.
I am getting this as well. I am guessing it is not affecting very many people though, since searching "the requested file was not found in any documentation set" in google is still only turning up four hits. And it is affecting my desktop but not my laptop.
Have either of you tried reinstalling Xcode?

Resources