Xcode: Using swift playground detect when running XCTest or PlaygroundPage - xcode9

Any of you knows if is a condition I can set the swift playground to differentiate when is been executed either by:
MyClassTest.defaultTestSuite.run() or by
PlaygroundPage.current.liveView = MyClass()
I'll really appreciate your help.

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.

Xcode 7.3/Swift 2.2 bug? Code builds in simulator but shows errors on device

The following swift code snippet compiles properly when built for the simulator, but if I select my iPhone 4 device (iOS 9.3.1) XCode complains:
if let result = (jsonobj["user"] ?? jsonobj["users"]!) {
if let item = result["userID"] as Int {
self.userID = item
}
}
The error points to the 'result' variable on the second line and says "Value of optional type 'AnyObject?' not unwrapped; did you mean to use '!' or '?'?"
The error makes no sense, as 'result' is unwrapped in the first line. Also, there was no problem before upgrading to XCode 7.3. As noted, if I switch to building for the simulator, the error goes away.
Should I post this as a bug? Does anyone have any insight?
UPDATE
When I first encountered this problem the device was not updated to the latest iOS build (9.3.1). I tried to make the compiler-suggested changes; this allowed the code to build but introduced errors when the simulator was chosen for a build. Also, the code crashed inexplicably when I ran it on the device.
I've subsequently updated the device to 9.3.1 and now the edited code runs without crashing, which enables me to continue development, but doesn't explain the difference with the simulator.
Next I created a new project and copied the erroneous code into the AppDelegate.swift file; the error appears again, however, it also appears for a simulator build. Making the recommended changes fixes the problem in both cases.
I will proceed by examining the build settings for both projects and see if there is a more specific cause for the difference in behavior between the device and the simulator.
Rewrite like this:
if let result = jsonobj["user"] as? NSDictionary {
if let item = result["userID"] as? Int {
self.userID = item
}
}
I had to provide an explicit type for 'result' in the first line:
if let result:AnyObject = jsonobj["user"] as? Int {

Xcode Beta 6 - Use of undeclared type 'CLLocationManagerDelegate'

I have just upgraded from Xcode 6 Beta 3 to Xcode 6 Beta 6. In Beta 3, everything worked fine and compiled like I wanted it to.
Right now, I cannot get CLLocationManagerDelegate to work, i.e. I always get the Use of undeclared type 'CLLocationManagerDelegate' - error message.
This is what my file looks like:
import UIKit
import CoreLocation
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate {
Additional info:
I have added the CoreLocation Framework (tried adding it within Xcode directly, also by drag-and-dropping the actual file from the folder, no changes)
I have had to reinstall Xcode 6 Beta 6 a couple of times before getting it to start (running OSX 10.9.4, always crashed on first startup)
As you can see, I import CoreLocation to my file.
CLLocationManagerDelegate does not autocomplete, it goes as far as CLLocationManager
Any ideas? I'm assuming something is not linked properly here.
Try to clean your build directory:
Product-->Clean
Product-->(Alt key) Clean Build Folder
Delete your derived data:
Window-->Organizer-->delete derived data
Another possible reason for the 'use of undeclared type' error is that your class is also within your test target, but the 'undeclared type' is not.
This was a bug in XCode. Was solved in Beta7/Xcode6.

SetAppThreadPriority: setpriority failed with error 45

Hello I have an issue with my app:
SetAppThreadPriority: setpriority failed with error 45
I am using Xcode 6 and I am not sure if this is the issue.
I am new to Xcode so perhaps this is expected behavior, but i found that i get this error if i have the GameScene.Swift file selected in the project navigator when i run the simulation. But if i have the top level folder selected it runs fine without this error.
By selected, i just mean clicked on so it's highlighted..
Other suggestions did not solve it for me.
if you are using storyboard, go to Targets -> General and check the Main Interface property if your storyboard is selected.
I'm confident this is a bug within the Xcode beta. I'd love to share why, but it's against Apple's TOS. There's nothing wrong with your code. You should submit a bug report to Apple: bugreport.apple.com
You are not setting the thread priority for your NSOperation. Here is an example in Swift that gives the error you are seeing and one that doesn't. I'm assuming the same error message will appear if you are using Objective-C
Does
let backgroundOperation = BackGroundSillyness()
queue.addOperation(backgroundOperation)
backgroundOperation.completionBlock = {
println("hello from completion")
}
println("hello from UI thread")
Doesn't
let backgroundOperation = BackGroundSillyness()
queue.addOperation(backgroundOperation)
backgroundOperation.threadPriority = 0
backgroundOperation.completionBlock = {
println("hello from completion")
}
println("hello from UI thread")

Getting strange debugger message: Assertion failed: (cls), function getName: what is this?

Since I upgraded from Xcode 3.2.3 to 3.2.4 and iOS 4.0.1 to iOS 4.1 SDK, when I set a breakpoint in my code and single-step over instructions, at each step, the debugger will spit one or more of that line:
Assertion failed: (cls), function getName, file /SourceCache/objc4_Sim/objc4-427.1.1/runtime/objc-runtime-new.m, line 3939
It doesn't happen on a specific line or for a specific instructions. I have a few breakpoints in my code and each time I hit one of those, the debugger starts spewing those messages. It doesn't seem to have any detrimental effect as the program works correctly. It's just very annoying to retrieve the information in the console when there are tens of those lines. I'm sure they're not displayed for nothing but I haven't found what the problem might be and what instruction might cause it. If I don't hit a breakpoint, then I don't see any of those lines. I did clean and rebuild my project multiple times to no avail.
Does anybody have any idea what this is?
I ran into this - and here's the reason mine happened: I had used
+localizedStringFromDate:dateStyle:timeStyle: in my code. Worked fine on the iPhone, but it's not available pre-4.0 SDK, so it coughed on the iPad. See if you're calling some routine that's either no longer available in the SDK, or available only in later versions. Frankly, I can't wait for 4.1 on the iPad!
-Owen
I'm also having this problem, in an iPad app originally written in Xcode 3.2.4 using the iOS 3.2 SDK, now being debugged in Xcode 3.2.5 using the 4.2 SDK, but only when I set the simulator to the 3.2 iOS Deployment Target (so I can run in the 3.2 simulator). Every stop at a breakpoint in the debugger, I get this assert repeated eight times. Single-stepping over a line gets two more.
What I can't understand is I haven't added any code to the project since I last run it in Xcode 3.2.4 and iOS SDK 3.2, so I can't have added any calls that were not present in that SDK or else it wouldn't have compiled.
Until someone finds an answer to this, I think the only workaround (so I can continue debugging my code in a 3.2 environment) is to reinstall Xcode 3.2.4 and use the 3.2 SDK and simulator.
I had this problem when I was running on simulator "iPad 3.2 simulator". This problem disappeared when I switched the simulator to "iPad 4.3 simulator"
I have exactly the same issue. I know it's not the complete answer but here's what I could find.
The relevant function getName looks like this:
/***********************************************************************
* getName
* fixme
* Locking: runtimeLock must be held by the caller
**********************************************************************/
static const char *
getName(struct class_t *cls)
{
// fixme hack rwlock_assert_writing(&runtimeLock);
assert(cls);
if (isRealized(cls)) {
return cls->data->ro->name;
} else {
return ((const struct class_ro_t *)cls->data)->name;
}
}
So gdb is complaining that the assertion assert(cls) is failing. Which means that getName somehow gets a NULL pointer as an argument.
Which is kinda funny, where could we be asking for the name of a NULL class?
Hope this helps...
I also have the same problem; I don't have a solution but I'm able to work around it. In short, I suggest you add more breakpoints...
I noticed in the call stack that it's actually the debugger that is misbehaving. The function gdb_class_getClass calls getName, presumedly this is passing NULL instead of (say) MyClass. The code that I'm trying to debug is a method of MyClass. So, thinking that the debugger has a problem with MyClass, I set a breakpoint at a line outside of any code of MyClass (ie the line that calls the method on MyClass) and hit continue when the program breaks. This seems to resolve the problem in my case. (Note that auto-continue doesn't work.)
To be clear:
//Set breakpoint here
[myClassInstance buggyMethod];
My buggyMethod is actually in another file:
...
-(void)buggyMethod {
//This is where I set my 'real' breakpoint
Hope that helps.
I'm having a similar problem, but mine is with creating a custom view with Core Text in it. As soon as my view's drawRect calls the line
CTFontRef titleFont = CTFontCreateWithName(CFSTR("Baskerville"), 40.0f, NULL);
It hangs the app, whether in the simulator or on the device. Bizarrely, I can rectify this by alloc-initing another UIKit text component in the View Controller's viewDidLoad method... I don't even have to add it as a subview. It's like it needs some common text elements loaded before Core Text can load in fonts.
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
}
Weird.

Resources