Thread 1: "-[Xylophone.ViewController buttonClicked:]: unrecognized selector sent to instance 0x7ff83a6074e0" - ios

Exception NSException * "-[Xylophone.ViewController buttonClicked:]:
unrecognized selector sent to instance
0x7faa47409400" 0x0000600002148690
I'm trying to make a xylophone app in which the buttons would play different sounds, there are 7 buttons however only the first button doesn't work, all other buttons work. on pressing the first button the app crashes.
Here is the code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func keyPressed(_ sender: UIButton) {
playSound(soundName: sender.currentTitle!)
}
func playSound(soundName:String) {
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
}
what is the issue here?

I faced the same issue and here's how I solved it:
right-click every button you have in Main.storyboard, and check the connection it has in the small menu like this:
When I had more than one connection it gave me this error.

Related

Swift audio playing from url

import AVFoundation
import UIKit
class ViewController: UIViewController {
#IBOutlet var button: UIButton!
var player: AVPlayer?
var playerItem:AVPlayerItem?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func didTapButton(urlRadio: String){
if let player = player, player.isMuted{
//stop playback
}
else{
do {
try AVAudioSession.sharedInstance().setMode(.default)
try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
guard let urlRadio = URL.init(string: "http://live.shtorm.fm:8000/mp3_rushtorm") else {
return
}
let playerItem:AVPlayerItem = AVPlayerItem.init(url: urlRadio)
player = AVAudioPlayer.init(playerItem: playerItem)
}
catch {
print("something went wrong")
}
}
}
}
shows error Exception NSException * "-[RozetkaRadio.ViewController didTapButton]: unrecognized selector sent to instance 0x7ff070f07a50" 0x00006000008c7210 after pressing button in emulator
using storyboard
Your issue is with this line of code. Specifically, the parameter urlRadio.
#IBAction func didTapButton(urlRadio: String){
It looks like you have changed the standard IBAction from what was set in storyboard. You cannot change the parameters in an IBAction as the storyboard no longer recognizes where to send the tap to.
Your IBAction should look something like this
#IBAction func didTapButton(_ sender: Any)
Whenever you see Unrecognized selector sent to instance you should immediately think "Something is not hooked up properly between my storyboard and my ViewController"
One quick way to look is by right clicking your controller scene name on the storyboard. You can see I commented out my SignIn IBAction function. If I wanted to remove it I would have to also remove the connection on the storyboard. You can see the storyboard will let me know by leaving a yellow warning label.

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x100813b50) fatal error

import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var audioPlayer : AVAudioPlayer!
let soundArray = ["dog","cow","bear","pig"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func dogSound(_ sender: UIButton) {
playSound(soundName: soundArray[sender.tag - 1])
}
func playSound (soundName : String) {
let soundURL = Bundle.main.url(forResource:soundName, withExtension: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
}
catch {
print(error)
}
audioPlayer.play()
}
}
You can see the image below I have a problem with unwrapping. I am new to the Swift language, and this is the 3rd day, I am trying to solve this problem but I can't find the solution. Can you help me and tell how to fix this nil thing? Cheers
fatal error: unexpectedly found nil while unwrapping an Optional value
Reason for error : The sound file being used doesn't exist in the project. Please check either the names or the extension(.wav, .mp3) of the sound files.
Detail description :
This error occurs when the value you are using doesn't exist, in your case the sound file that you are trying to use by passing names in the array doesn't exist.
Possible reasons :-
1) The sound file that you are using doesn't exists in the project
2) There is some name or extension(.wav, .mp3) mismatch of the sound file in the project and their name being used in code.
Debugging issue :-
1) Try print the name of the sound file (soundArray[sender.tag - 1]) as 1st line in
func playSound (soundName : String) {
}

WKNavigationDelegate Crashing App on Assignment

I'm working on a simple web wrapper application for iOS, and I'm having some issues with WKWebView and WKNavigationDelegate. I want to use the didFinishNavigation function from WKNavigationDelegate, so I can grab information from the URL query on navigation (namely a session GUID). My program launches correctly and loads my webpage when I comment out the "webView.navigationDelegate = self" line, but when I include that, my app crashes immediately with the following errors:
" -[UIWebView setNavigationDelegate:]: unrecognized selector sent to instance
0x7f8251e058f0"
"*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[UIWebView setNavigationDelegate:]: unrecognized selector sent to
instance 0x7f8251e058f0'"
I noticed that both of these error messages include "UIWebView," when I'm trying to use WKWebView, so I tried to use the "custom class" field on the webview from the identity inspector part of the storyboard, but when I try to run after that, I get "(lldb)." Any help/insight would be appreciated, I'm including my code below:
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
print("view did load")
webView.navigationDelegate = self
loadURL("http://mydomain/login.html")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func loadURL(targetURL: String){
if let url = NSURL(string: targetURL) {
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
}
}
private func checkDomainGetSessionGUID(){
print ("we are here")
if let query = webView.URL?.query {
let queryArr = query.componentsSeparatedByString("&")
var parsedQuery : [String: String] = [:]
for field in queryArr {
let parts = field.componentsSeparatedByString("=")
parsedQuery.updateValue(parts[1], forKey: parts[0])
print ("key = \(parts[0]) and value = \(parts[1])")
}
}
else {
print ("didn't enter the if let")
}
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
print ("delegate")
checkDomainGetSessionGUID()
}
}
PROCEDURE 1:
Step-1: Check UIElements that you are using in Storyboard design. if you had used Web view instead of using **WebKit View this error might come.Check your IBOutlet connection.
Step-2: Check your IOS deployment target, It must be IOS 11 and above because of UIWebKit View was released in IOS 8 but it contains a bug that was fixed in IOS 11 only. So set your deployment target 11 and above.
Step-3: Check your info.plist property. The following property should add in the listApp Transport Security Settings -> Allow Arbitrary Loads -> YES
PROCEDURE 2:
If in case you want deployment target as IOS 10 or below IOS 11 means you can implement like this
Step-1: Create a new UIViewcontroller with its swift ViewController file. And add below-given code to run your URL:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string:"https://www.apple.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}}
I hope this might be helpful to you...
I was getting this error inside (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
I removed the line [super webView:webView didFinishNavigation:navigation]; and everything worked as I expected, I'm not sure if it's hacky though.

SIGABRT error in swift 2

I recently updated my app to Swift 2, and had one error, which I solved thanks to you guys.
And now, I have a second error, which is at runtime, when I press the one button to play a sound. It is a signal SIGABRT error.
Here is the error message I get in the debug console:
2016-01-25 09:16:09.019 WarningShot1.0.0[291:19030] -[WarningShot1_0_0.ViewController playMySound:]: unrecognized selector sent to instance 0x135547d30
2016-01-25 09:16:09.021 WarningShot1.0.0[291:19030] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[WarningShot1_0_0.ViewController playMySound:]: unrecognized selector sent to instance 0x135547d30'
*** First throw call stack:
(0x182835900 0x181ea3f80 0x18283c61c 0x1828395b8 0x18273d68c 0x18755fe50 0x18755fdcc 0x187547a88 0x18755f6e4 0x18755f314 0x187557e30 0x1875284cc 0x187526794 0x1827ecefc 0x1827ec990 0x1827ea690 0x182719680 0x183c28088 0x187590d90 0x10005e2e0 0x1822ba8b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
Also, this is the part of the code where it throws this error, in the second line, where the class is declared:
import UIKit
#UIApplicationMain
-> class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
What is happening here? What am I missing / misnaming? What do I need to change in my code to get ot running again. This app is ridiculously simple, and worked for months under the last version of Swift. Why is it now giving me errors?
Thank you for your help.
Here is the code for my ViewController.swift file:
import UIKit
import AVFoundation
import CoreMotion
class ViewController: UIViewController {
var myPlayer = AVAudioPlayer()
var mySound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("RemSound_01", ofType: "wav")!)
func initYourSound() {
do {
try myPlayer = AVAudioPlayer(contentsOfURL: mySound, fileTypeHint: nil)
myPlayer.prepareToPlay()
// myPlayer.volume = 1.0 // < for setting initial volume, still not perfected.
} catch {
// handle error
}
var motionManager = CMMotionManager()
var currentMaxAccelY : Double = 0.0
func viewDidLoad() {
super.viewDidLoad()
initYourSound()
// Do any additional setup after loading the view, typically from a nib.
//set motion manager properties
motionManager.accelerometerUpdateInterval = 0.17
//start recording data
// motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: {
// (accelerometerData: CMAccelerometerData!,error:NSError!) -> Void in
// self.outputAccelerationData(accelerometerData.acceleration)
// if(error != nil) {
// print("\(error)")
// }
// })
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: {
(accelerometerData,error) in outputAccelerationData(accelerometerData!.acceleration)
if(error != nil) {
print("\(error)", terminator: "")
}
})
}
//func outputAccelerationData(acceleration : CMAcceleration){
// accY?.text = "\(acceleration.y).2fg"
//if fabs(acceleration.y) > fabs(currentMaxAccelY)
//{
// currentMaxAccelY = acceleration.y
//}
// maxAccY?.text = "\(currentMaxAccelY) .2f"
//}
func outputAccelerationData(acceleration : CMAcceleration){
if fabs(acceleration.y) >= 1.25 {
myPlayer.play()
}
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func playMySound(sender: AnyObject) {
myPlayer.play()
}
// self.resetMaxValues()
// #IBOutlet var accY: UILabel!
// #IBOutlet var maxAccY: UILabel!
// #IBAction func resetMaxValues() {
// currentMaxAccelY = 0
// }
}
}
"unrecognized selector sent to instance" means that there is a mismatch between the action-name in "addTarget()" and the name of the function you want to call. Probably something with the parameters of the function.. It's hard to say without seeing any code.
action: Selector("playMySound:")
would expect to find a function:
func playMySound(sender: AnyObject?) {};
To easier track what's happening, you might add a symbolic breakpoint for all exceptions. You do that in Xcode on the "exceptions" tab (left part of the window) and when an exception is thrown, Xcode stops like usual and you might look up the stack trace. If the call is synchronous, you should easily find and see your mistake.
EDIT: Oh well, you seem to have done the user interface using a XIB file. The mistake could be, you wired the button's action in the XIB file to the view controller. If you later change the method's signature (parameter, name, etc.), UIKit can't find the method. Open the XIB and fix your error. ;-)

AVFoundation Value of option type 'String?' not unwrapped, App Crashes, won't play sound

I'm trying to play a simple sound when I push a button. xcode is forcing me to use a "!" for my NSURL for the audio file, I followed other tutorials for how to play a sound in swift and for some reason I keep getting this error, why!? Code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("buttonSound", ofType: "mp3")
let fileURL = NSURL(fileURLWithPath: path!)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.prepareToPlay()
}
#IBAction func button21(sender: AnyObject) {
player.play()
}
}
When I do add the "!", the app will load without crashing, when I press the button the app crashes and the log outputs "fatal error: unexpectedly found nil while unwrapping an Optional value"
Good to see your problem got solved. Just adding to the conversation:
I had the same issue as you and I followed the advice given by other people here, but it didn't get rid of my problem (unexpectedly found nil while unwrapping an Optional value). I'm using Xcode 6.1 and the thing that solved it for me was deleting the file and adding it again except this time, instead of dragging the file in, I did it by right-clicking the project folder and selecting the "Add Files to your_app's_name" option.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var myPlayer = AVAudioPlayer()
var yourSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("alarm2", ofType: "mp3")!)
func prepareYourSound() {
myPlayer = AVAudioPlayer(contentsOfURL: yourSound, error: nil)
myPlayer.prepareToPlay()
}
override func viewDidLoad() {
super.viewDidLoad()
prepareYourSound()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func playMySound(sender: AnyObject) {
myPlayer.play()
}
}
HERE is the project sample link
Sample Project
A bit old now, but I had the same problem recently.
The way I fixed it was to select my file (an mp3, too) and go into the File Inspector and make sure the Target Membership was checked for my project.

Resources