Play Sound in Swift SpriteKit project? - ios

When I run this code.
runAction(SKAction.playSoundFileNamed("Click.mp3", waitForCompletion: false))
My app was Crashed:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Resource Click.mp3 cannot be found in the main bundle'

verify that the file exists in the project.
instantiates the variables in the file first and then make a method for breeding.
if the file exists in the project you should do the following:
var sound = SKAction.playSoundFileNamed("sound.mp3", waitForCompletion: false)
...
override func didMoveToView(view: SKView) {
playSound(sound)
//call playSound method when you want
}
func playSound(sound : SKAction)
{
runAction(sound)
}
in this mode don't crash

This may be the answer some people are looking for:
Audio files DO NOT go in Assets.xcassets!
I've had the same issue, and tried seemingly every slight code change as suggested by various StackOverflow answers, but nothing worked.
I only found this one answer that solved my issue: I had been adding my sound files to Assets.xcassets, where my graphics are. It turns out you need to add them to the project bundle (where the .swift files are, etc) — just drag the files to the Project Navigator list on the left of the screen.
Not sure why it's like this as it seems intuitive to include sound files as "Assets".

I had this exact problem for the last hour! I had to go a different route, because I tried multiple things to get this simple line of code to work and failed. It's a little more code, but this solved my problem: https://stackoverflow.com/a/24073071/586204.

Related

Use of unresolved identifier - app development with Swift Project 2

Sorry - I realise this is a complete beginner question, but I've googled for half a day now and still can't resolve the issue myself.
I'm using xCode 8.3 and trying to complete the apple - app development with swift course - end of unit project 2. I'm told (by the Apple book) I should be able to run the app without build failures, even if it isn't finished.
I get an unresolved identifier error when I add the following code to my ViewControler file, inside the class ViewController: UIViewController.
func updateUI() {
correctWordLabel.text = game.formattedWord
scoreLabel.text = "Wins: \(totalWins), Losses: \(totalLosses)"
treeImageView.image = UIImage(named: "Tree \(currentGame.incorrectMovesRemaining)")
}
xCode suggests I change it to Game.formattedWord, but when i do get 'Instance member 'formattedWord' cannot be used on type 'Game' ViewController.Swift'.
Could someone please help?
I've checked the sample code from Apple about 100 times and they are def saying it should be game.formattedWord in the code.
Thank you!
Try correctWordLabel.text = currentGame.formattedWord
I think it’s a typo.
Earlier in your code you create an instance of the Game struct called currentGame so you are accessing the formattedWord variable inside that instance. That’s why you couldn’t change it to Game. Game is like the blueprint of the struct. currentGame is your actual ‘thing’ Hope that makes some sense.

Today-Widget "Unable to load" error

From time to time widget crashing with "unable to load" error.
Is anyone know how to fix it?
Widget haven't requests to server or smth else.
Unable to load in today extension mostly appears when:
You extension crash due to some reason
It takes more memory than what is provided by the system. (Memory Limit : max 16MB approx.)
Debug your app extension to find out the exact problem.
Refer to Xcode's Debug Gauge for Memory and CPU utilization.
Edit:
Debugging today extension
You can debug your extension the same way you debug your main project. Just select that particular target scheme in your Xcode and run the project.
Now try using the breakpoints and other print statements in the extension’s code and you are good to go. Happy coding..😊
REBOOT the device.
This saved me.
I have faced this error
I used a custom view. But forgot to check Is initial viewController.
Set an entry point form "show attribute inspector" as an initial view controller
I have faced the same issue where it wasn't showing anything. Even my debug option was not working. I found an article online which helped me a lot. I would like to recommend this here.
Most of the time it is the size of the content view that crashes the widget. in that case, use this code snippet in TodayViewController.
Code snippet
override func viewWillAppear(_ animated: Bool)
{
var currentSize: CGSize = self.preferredContentSize
currentSize.height = 200.0
self.preferredContentSize = currentSize
}
Link for further research.
Make sure you have more than 0 rows
I have built a today-widget similar to Building a Simple Widget for the Today View.
I had none of the above issues. Mine was 0 row (I had no data for this particular day and hence, 0 row). I did not expect that it could be the problem since in the main-app, you can have empty table-view.
If you see unable to load message, make sure you have at least 1 row.
Set this in viewDidLoad:
extensionContext?.widgetLargestAvailableDisplayMode = .expanded
In my case NotificationCenter.framework was accidentally deleted from Link Binary With Libraries in Build Phases tab in widget target.

PureLayout on device: unrecognized selector sent to instance

today I found out that there is an issue with my project. I can't run it on a real device, because I am getting an 'unrecognized selector sent to instance' error when it reaches the part of code that comes from a pod that I am using. I can run the app if I comment the part with this code.
The problem here is that I did not encounter this problem before and it just came out of nothing.
Under linked frameworks and libraries, my pod is linked as 'optional', because I get 'dyld: Library not loaded' error if it is marked as 'required'. Bitcode is enabled as well, changing this didn't make any difference.
Currently I am using XCode 7.0 (7A220) and Cocoapods version 0.38.2.
I'd be glad for any given tips on this.
#Edit
I've found out, that I was able to run other pods. The issue comes with PureLayout pod.
#Edit2 Code
class MainViewController: UIViewController {
var label : UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.setupView()
}
func setupView() {
self.view.backgroundColor = UIColor.whiteColor()
label = UILabel()
self.view.addSubview(label)
label.autoPinEdgesToSuperviewEdges()
}
}
This view controller is displayed when app is launching. This code represents the whole situation as app crashes even on this simple view -
[UILabel autoPinEdgesToSuperviewEdges]: unrecognized selector sent to instance.
Edit
Same code works on release build config. Does anyone know why?
The best thing I can suggest is start all over from the vary beginning. Depending on how much code you have this might be intimidating, but it is the best I have to offer. But my advice is this: don't move onto something else until the bug is obliterated, doing so can save you a lot of stress.

Xcode 6.0.1 Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

I am getting this error on archive:
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
How to solve it?
Please see the screenshot.
This problem occurs when the Swift optimization level is not set to None for Release. Set the value to None and the issue goes away.
Open up your project and click on the projects root directory.
Click the build settings tab.
Search for Swift Compiler - Code Generation and under Optimization Level make sure Release is set to None.
EDIT
After upgrading to Xcode 6.1 these instructions caused other issues when archiving (building for debug/device worked fine). Setting the optimization to Fastest allowed me to archive again. There are apparent issues with Swift compiling still (archiving specifically).
Can't archive working 6.0.1 Swift project in Xcode 6.1 / Segmentation fault: 11
EDIT
I was not able to fund the Build Settings tab, until I read this answer.
how to find the build settings tab
This occurred for me when I had two of the exact same files, and also when I was missing I file I didn't know I had deleted. I clicked on the error message, and just above the error, it shows you what file you have more than 1 of or are missing.
You can click the Product in the navigation and choose the "Clean" button; it will clean all compile error in your project. Then, you can debug for the latest error.
Deleted files reference keep in Build Phase and that's why it gives this error. Remove reference from there as well.
Project> Target > Build Phase
Under this section you will find your deleted files in red colour. Remove these files error will resolve.
I am not sure if it has one solution.
I recommend you to check the differences between your last git commit, and comment on/off the changes.
In my case, my code was
let anArray = ResultDict["ResultSet"] as [[NSDictionary : AnyObject]]
for aDict : NSDictionary in anArray {
let anObject = ObjectType(ObjectDict: aDict)
objectList.addObject(aDict)
}
no warning on the line, i got the same exit 1 compile error
then i changed it to the below it has compiled.
let anArray = ResultDict["ResultSet"] as [[NSDictionary : AnyObject]]
for aDict in anArray {
let anObject = ObjectType(ObjectDict: aDict)
objectList.addObject(aDict)
}
I don't know if this is really an answer, but...
I had the same issue. App worked when building/running, but archiving failed with "...swiftc failed with exit code 1", with no other helpful message at all. Luckily, when I tried to build my app with Nomad's ipa build, I got:
The following build commands failed:
CompileSwift normal arm64 /path/to/erroneous/TableViewController.swift
So I started commenting out sections of that file and tracked the problem down to a tuple assignment.
// MARK: - Table Data
private var tableData: [(sectionName: String, item:ListItem)] = []
private func refreshTableData() {
// let labor = ("Labor", laborListItem) // DOESN'T ARCHIVE
let labor = (sectionName: "Labor", item: laborListItem) // ARCHIVES
tableData = [labor]
tableView.reloadData()
}
So apparently the compiler wanted the elements in thast tuple named (as defined by the type of tableData).. but only for archiving? The Dumb thing is, I use this same pattern in other view controllers, and the compiler seems to be fine with those.
For the record my Code Generation -> Optimization Level was set to None for debug and release.
Hope this helps someone! It took hours to figure this out.
It happened to me when I didn't put the parenthesis at the end of a call of a function:
let var = self.getNextPrimeNumber
solved it by:
let var = self.getNextPrimeNumber()
In my case, it was caused by duplicate files, using the same name, in my project directory. As soon as I removed them, the error was gone.
This happened to me when I used static inline function from swift file
The function looks like this
static inline void openURLInSafari(NSString * _Nonnull urlString) {
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];}
I just had the same thing occur. I hunted down the cause to one file that caused the error even when empty. Examining the file, I discovered it had the wrong character set. When I set it to UTF-8, the error vanished. I think that it was decoding it with the wrong character set.
From this I surmise that the error simply indicates that something has happened that the compiler was unprepared for. Sorry that isn't very helpful to most people, but it may help to check your characters sets.
one more case that can lead to this error which just took me hours to track down: a failable initializer that always returns nil.
i had an initializer that looked like this:
init?(object: MyObject) {
if object.importantProperty {
// initialize
}
return nil
}
when what i meant was:
init?(object: MyObject) {
if object.importantProperty {
// initialize
}
else {
return nil
}
}
fixing the initializer made the error go away.
If using Core Data:
I had a Core Data entity for which I created the NSManagedObject subclasses (with Xcode's help). In addition, the entity was configured to generate code automatically (see screenshot), so basically 2 classes existed during runtime. Just switch the option to Manual/None and it won't generate it.
This error occurred for me after I noticed that a few of my .swift files were inexplicably in the wrong directory -- one level above my Xcode project directory. When I noticed this, I moved them into the main project directory and cleaned the project, thinking everything would be fine. However, upon building the project I got the above-mentioned "failed with exit code 1" error. Just above the error message it listed the files I had just moved, indicating that it couldn't find them in the directory where they used to be. In addition to the error message, the files I moved were now showing up as red in the file navigation pane.
For each of the files in question what I did to resolve this was:
- Select the file from the list of files in the Xcode file navigation pane,
- Click on the little page icon in the rightmost pane of Xcode, which opens a file attributes pane,
- Click on the little folder icon underneath where it says "Location" in the file attributes pane,
- Choose the new location for the file,
- RESTART Xcode for the above changes to really do anything.
this error comes from missing files so the compiler couldn't find the files and keep alerting.
Follow these steps to rebuild your app:
Look up for the red and invisible files within workspace
Remove their reference
Re-add files
Re-compile
I experienced this error after performing a git merge. I solved new Xcode warnings and the project can be compiled.
Xcode 7.2.1 is used in my case.
In my way the error was due to UIDevice.currentDevice() in ((UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8.0)
After commenting this all starts work fine.
XCode 7.2
in my case , at your project target Build Setttings, in Other Swift Flags,jsut delete the String "-serialize-debuggin-options"
enter image description here
I had a resolution very similar to RyanM, where with an excess of hubris I tried to assign a variable to the default value of an inner function:
Fails to compile (though does not crash SourceKit):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
func itemCell(_ indexPath: IndexPath = indexPath) -> UITableViewCell {//...}
Succeeds:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
func itemCell(_ indexPath: IndexPath) -> UITableViewCell {//...}
One possible reason that this can happen is perhaps because you have deleted a file but not removed references to it. This will mess up the pbxproj file. I would check to see if that is the case.
check "Development Pods" Folder all listed Frameworks path.
In my case swift development snapshot was selected instead of xcode 9.2. here are the steps and image.
keep xcode on screen and click on xcode top menu bar.
Than go to toolchains option and check on xcode 9.2. thats it.
Happy Coding!!!
So, I had the above and narrowed it down to a TFS issue with locking the file but only when I pasted or did any other edits besides small copies or manual typing. I noticed the original file would compile, but my edits wouldn't, even though they were syntactic OK. Also related is unable to save document: xcode The document "..." could not be saved
The fix for both was:
Duplicate working version.
Paste fully-merged new code into duplicate.
Copy and paste old file over new one. (I personally just renamed the old one to something else, then pasted duplicate and renamed it, too. Guessing both work since I pasted directly earlier for reverts during tests to see).
Voila. Lazy way to bypass merge-locking issue. Apparently full file-pastes are just fine, while edits aren't. Shared since the other answers don't seem to be as lazy as this. ;)
Note: I am suspecting a non-UTF-8 character made its way somewhere, but pastes worked in older versions so I don't know where, or if relevant.
In my case, the error was the result of missing files that were generated by Xcode. I tried the regular clean Opt+Shift+K and it didn't clean up all the errors. I found a post on the Apple Developer site that recomended going to the Product Menu in Xcode, holding down the opt key, and selecting Clean Build Folder. This appears to be a more comprehensive build as it pops up a modal dialog for you to confirm.
Just go to the "project setting" and click on the "build phaces" after that you will find targets in that u have to delete the test file like my project name "WER" so its showing like this WER&TEST so just delete that and clean ur project and run .........

swift failed with exit code 1 while compiling in Xcode - possibly related to Bridging-Headers

I have an Obj-C Project I'm trying to migrate to Swift. I did succeed with various classes but recently ran into an issue I can't seem to make sense of. When I try to compile my current code base I get the following (SUPER UNHELPFUL ERROR MESSAGE)
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
My only assumption is its somehow related to my bridging-headers but Xcode isn't giving me enough information to figure out if this is actually true.
I'm using Cocoapods to add the CorePlot to my project. I'm trying to migrate the following class to Swift:
Obj-C Class (ScatterPlotContainer.h)
#import <Foundation/Foundation.h>
#class CPTScatterPlot;
#interface ScatterPlotContainer : NSObject
#property (nonatomic, strong) CPTScatterPlot *ahrsAlt;
#property (nonatomic, strong) CPTScatterPlot *calibration;
#property (nonatomic, strong) CPTScatterPlot *coreAlt;
#property (nonatomic, strong) CPTScatterPlot *pitch;
#property (nonatomic, strong) CPTScatterPlot *roll;
#property (nonatomic, strong) CPTScatterPlot *slip;
#end
Obj-c Class (ScatterPlotContainer.m)
#import <CorePlot/CPTScatterPlot.h>
#import "ScatterPlotContainer.h"
#implementation ScatterPlotContainer {
}
#end
Swift Conversion
import Foundation
class ScatterPlotContainer : NSObject {
public var ahrsAlt : CPTScatterPlot;
public var calibration : CPTScatterPlot;
public var coreAlt : CPTScatterPlot;
public var pitch : CPTScatterPlot;
public var roll : CPTScatterPlot;
public var slip : CPTScatterPlot;
}
My bridging headers file
#import <CorePlot/CPTScatterPlot.h>
What I've tried thus far
When I comment out the #import <CorePlot/CPTScatterPlot.h> from the Bridging headers file - I get an error in swift because it doesn't know what CPTScatterPlot is
I've also tried #import <CPTScatterPlot.h> which didn't work either.
Thoughts
So the only thing I can think of is perhaps because I'm using a cocoa pod there is some sort of module name I need to add. The error message really isn't that useful. Does anybody have a suggestion about some blaring error I've made or how to get a more descriptive error message to figure out what is going on?
I did the same all answer says but mine issue was not resolved. I did figured out that issue was related to broken function call.
A function syntax was not wrong but its calling mechanism was wrong.
To check the exact error for this issue check following:
Select issue navigator > Click on error will show logs for error > In that select All Messages tab.
This will show all detail logs for this error.
Scroll down and You got logs like, in my case
So, by reading this I figure out that something wrong with function calling. I browse my code and resolved it, Below was correct and wrong code.
Wrong Way:
var region = MKCoordinateRegionMake(self.mapView.userLocation.coordinate, span)
// It will not shown error here but when you build project compiler shows error.
Right Way:
let region = MKCoordinateRegion(center: self.mapView.userLocation.coordinate, span: span)
I run into this last night and nothing above was solving my problem.
I was about to do something very bad at my laptop when I saw, all by pure luck, that ONE (1) file was is text encoding set to UTF-16 ?!?! WTF??
This was the last file I was working on, and probably, one bad cut/paste "import" a strange character into the arena. I did a cut/paste of my code in this file to a bare bone text editor. I deleted the file, recreate it and paste back my code... and voilà! it work.
So do the above, but also check your file encoding! :-)
I had the same error message.
What helped, was to set the optimization level in the swift compiler settings to None.
This is not really a solution for me and I think that's one of the many bugs in the swift compiler.
Another solution for this issues is to check that you don't have 2 or more files with the same file names. It solved the problem for me.
Thank you #Kampai for the advice on going through the error log message. I read through, and some files were missing:
<unknown>:0: error: no such file or directory:
Somehow, some files were removed during a pull from GitHub. The files are in the directory, but not in the Xcode project.
Right click on a folder and click 'Add files to ...' to manually add missing files to Xcode. That fixed the problem for me.
This happened to me several times already, but now I know how to fix it \o/
I was getting the same error for including this code in a didSet block:
didSet {
// Test whether this view is currently visible to the user.
if super.isViewLoaded() && (super.view.window != nil) {
// (build fails even if this block is empty)
}
}
It took a lot of trial/error to hunt this down. Removing super. allowed the build to proceed.
had a horrible time with this bug for over 3 hours by meticulously going from file to file and reverting the changes and seeing if that file had the issue in it. I tried the first answer but didn't give me any answers. Found the issue and it was because I had a non computed property named the same as a computed property of a subclass. I really hope the debugger becomes more robust with handling these sorts of cases in future updates :(
Simply deleting derived data and cleaning helped me
1) Identify the file there the problem is. You can copy and paste the compilation instruction to the console and the last screen will contain the error description. Note the pid number there the problem was identified. Then scroll up and find the pid and related instruction - there will be one file per pid, so you will find the file you have problem it.
2) Look through the file and check all you last changes. If you have git initialized you can use
git diff <file name>
As for #Kampal, I'm still struggling to figure out how much to specify in a function call. For instance, creating a UIColor object sometimes requires that UIColor be specified, and sometimes doesn't.
These both work:
playButton.backgroundColor = .darkGrayColor()
playButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
This yields the exit code 1 error on compilation, without any debugger warning. #time-sucking debug vortex
playButton.setTitleColor(.whiteColor(), forState: UIControlState.Normal)
So I have a new rule: when using a function that takes more than one parameter, be explicit.
Now back to playing swift: AVOID THE VORTEX
Since everyone else has been showing theirs, I'll show mine:
class Foo : UIView {
var pathPosition:Double = 0.0 { didSet {
pathPosition = min(max(0.0, pathPosition), 1.0) // crashes if this line is present
self.pathPosition = min(max(0.0, pathPosition), 1.0) // but not here
}}
}
Incredibly, this does not come up in Playground, but does fail when placed in code in a framework. Although it is legal syntax (used to work, still works in playground), the Swift compiler seems to want pathPosition to be qualified with self.. Note that is (relatively) old code and used to compile, maybe something broke in 6.1.
Edit:
I feel like I am going insane, but it feels like there is a greater complexity problem going on here, where surrounding code can impact this problem. I saw things compile last night, changed some code and settings again today, and it failed on me again. Today, I had to hack in a bunch of really stupid code to get it to work:
var pathPosition:Double = 0.0 { didSet {
// bug: insane!! - have to clobber the value before resetting!
let bugOldValue = pathPosition
self.pathPosition = 1.0 // fails without this nonsensical line!
self.pathPosition = min(max(0.0, bugOldValue), 1.0)
}}
For what it's worth, the actual error message I got, per the helpful instructions above, was:
PHI node has multiple entries for the same basic block with different incoming values!
%14 = phi double [ 1.000000e+00, %10 ], [ %11, %10 ], [ 1.000000e+00, %9 ], [ 0.000000e+00, %9 ], !dbg !4818
label %10
double 1.000000e+00
%11 = phi double [ %7, %entry ], !dbg !4815
LLVM ERROR: Broken function found, compilation aborted!
I'm scared for tomorrow.
I just had this same error, the problem was that I had overridden a method with a non-optional parameter and had made the parameter optional in the override. (the method parameter below)
func logNetworkCallDurationForMethod(method:String, path:String, milliseconds: UInt) {
}
override func logNetworkCallDurationForMethod(method:String?, path:String, milliseconds: UInt) {
}
Ran into this issue today actually. Was the result of a recent pull from git on a project where a file had been deleted, but it didn't update in my local project.
Clicking on the error brought up the location of the "missing" file, went and deleted it's reference in the Project Navigator. Fixed the error, did a clean, and compiled successfully.
This happened to me when trying to reference a method from an inmutable protocol argument(by mistake, I thought the member was a property):
Having an interface as follows:
public protocol NSValidatedUserInterfaceItem {
func tag() -> Int
}
Compilation crash
func validateUserInterfaceItem(anItem: NSValidatedUserInterfaceItem) -> Bool {
print(anItem.tag) // oopsie, tag is a function
return false
}
Compilation success
func validateUserInterfaceItem(anItem: NSValidatedUserInterfaceItem) -> Bool {
print(anItem.tag()) // this is cool for swift
return false
}
This happened to me and after reading the log in issue navigator I found out that I have two swift files with same name. This was creating the issue and I was getting build failed.
I got this error due to a missing file in my project. Added this file again and voila everything worked.
In my case it was wrong method overriding. Base class:
open func send(_ onSuccess: #escaping ((SomeType) -> Void)) -> SomeType { }
Subclass:
open override func send(_ onSuccess: ((SomeType) -> Void)) -> SomeType { }
As you see #escaping is missing. Swift3 converter in XCode8 doesn't consider inheritance relations, moreover, that type mistakes aren't marked as errors.
In My Case it was Simulator bug just uninstall app from simulator and clean project then run project.
I had accidentally dragged symlinks (aliases) to source files into the project instead of the actual files.
I had CoreData generated files twice (and added myself). Check the files are not duplicate.
Unfortunately this error is often caused by a glitch inside Swift's compiler. It is not always easy to find the reason. If cleaning doesn't work, my suggestion is to try to comment the last code you wrote (even the whole file if necessary). Usually commenting the last code you entered would restore the compilation and you'll get more meaningful errors. From there on you have to try to uncomment the code piece by piece until you get to the instruction which caused this error. The Swift compiler is still pretty young and from time to time it reports weird errors. These kind of errors are completely useless, because instead of helping the developers they only confuse them even more. I would suggest Apple to change the compiler to give more detailed information and avoid this annoying error from appearing anymore.
NSString const *kGreenColor = #"#00C34E";
I had above line in my Constant.h file. which was meant for preprocessors only.
Removing that line worked for me.
moving the Bridge file to project level resolve my problem.
In my case I had renamed a file. After committing I found that the file name still hasn't changed in the Xcode project (not sure why), the file was greyed out. Changing the name and committing again did the trick.
So we have to keep an eye out for this error, when making changes to files using source control.
In my case deleted a couple of files directly from SourceTree but their reference was still there in Xcode. Logs show their names. Removed them and error went away.

Resources