call can throw error message Swift 2 - error-handling

I just converted my app to Swift 2, and of course, am getting one error message:
"Call can throw, but it is not marked with 'try' and the eror is not handled"
I did search here for how to fix this, but the answers are even more confusing to me than the error itself. LOL.
My application worked perfectly until I converted it into Swift 2. Wonderful...
var myPlayer = AVAudioPlayer()
var yourSound1 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("RemSound_01", ofType: "wav")!)
func initYourSound() {
myPlayer = AVAudioPlayer(contentsOfURL: yourSound1, fileTypeHint: nil)
myPlayer.prepareToPlay()
myPlayer.volume = 1.0 // < for setting initial volume, still not perfected.
}
The error throws in the following line:
myPlayer = AVAudioPlayer(contentsOfURL: yourSound1, fileTypeHint: nil)
How am I supposed to fix this? I understand that Swift is trying to "universalize" error handling, but doing so by breaking even the simplest of code seems silly to me.
Thank you for your help.

Here is the pattern you are looking for.
<throwing function> // compiler error in Swift 2
do { try <throwing function> } catch { }
In catch you usually get an error that you can handle further.

This works in Swift 2.0, put it in your viewDidLoad method ...
do {
try AudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, fileTypeHint: nil)
} catch {
print("errorin do-try-catch")
}
where ButtonAudioURL is
var ButtonAudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Besides", ofType: "mp3")!)

Related

AVCaptureSession Crashing when using webRTC

I am using WebRTC and its using AVCaptureSession. It works fine a few times but sometimes its getting crashed with this Exception.
Assertion failed: (_internal->figCaptureSession == NULL), function
-[AVCaptureVideoPreviewLayer attachToFigCaptureSession:], file /BuildRoot/Library/Caches/com.apple.xbs/Sources/EmbeddedAVFoundation/EmbeddedAVFoundation-1187.37.2.1/Aspen/AVCaptureVideoPreviewLayer.m
I recently had this problem aswell. In my code i kept an instance of AVCaptureOutput and added and removed it. When trying to add the same AVCaptureOutput instance to the same capture session again, this error appeared.
This is how i solved it:
private var _captureOutput: AVCaptureOutput?
var captureOutput: AVCaptureOutput {
guard let captureOutput = _captureOutput else {
let photoOutput = AVCapturePhotoOutput()
photoOutput.isHighResolutionCaptureEnabled = true
_captureOutput = photoOutput
return photoOutput
}
return captureOutput
}
Initialize the instance once when needed and when removed, also nullify it.
captureSession.outputs.forEach { [weak self] output in
self?.captureSession.removeOutput(output)
self?._captureOutput = nil
}
Before using instance of RTCCameraPreviewView you have to nill'ify its captureSession and assert will go away. Faced same issue.

what is the proper syntax for the following expression in swift 3?

as you can guess, this is an issue regarding swift's whole API renovation. I've read the documentation extensively but can't seem to lay my finger on a proper workaround.
I am receiving the error
Value of type 'Error' has no member 'userInfo'
on the following line:
else if let secondMessage = error?.userInfo["error"] as? String
of this block:
let query = PFQuery(className: "Images")
query.whereKey("Subject", equalTo: self.subjectName)
query.findObjectsInBackground { (objects, error) -> Void in
if error == nil {
// do something
}else if let secondMessage = error?.userInfo["error"] as? String {
// do something
}
Any suggestions? feel's like I'm missing something painstakingly obvious... dev block i guess :(

Is it possible to catch an Objective-C error from Swift code?

I would like to do something like:
try {
SomeObjectiveClass.someMethod()
catch Error {
print("Recovered objc crash from Swift!")
}
I'm building an app where I type some visual constraints and I get the result or a message about any mistake.
Now, every time I type wrong constraints the app crashes, but I'd like to display a dialog with the error and let the user try again.
In my situation I don't have the "NSError-to-throws" automatic translation.
Consider this class:
#implementation SomeObjectiveClass
+ (BOOL)someClassMethodWithError:(NSError **)error {
// some something that
if (everythingOk) {
return true;
} else {
if (error) {
*error = [NSError errorWithDomain:kMyDomain code:kSomeErrorCode userInfo:#{NSLocalizedDescriptionKey : #"Some error message"}];
}
return false;
}
}
- (BOOL)someInstanceMethodWithError:(NSError **)error {
// some something that
if (everythingOk) {
return true;
} else {
if (error) {
*error = [NSError errorWithDomain:kMyDomain code:kSomeOtherErrorCode userInfo:#{NSLocalizedDescriptionKey : #"Some error message"}];
}
return false;
}
}
#end
You can then catch those errors like so:
do {
try SomeObjectiveClass.someClassMethod()
// or
let object = SomeObjectiveClass()
try object.someInstanceMethod()
} catch {
print("Recovered \(error) from Swift!")
}
Note, this catching of errors should not be confused with exception handling which we used to be able to do in Objective-C. Exceptions should be eliminated during the development process. The above is for legitimate runtime errors (e.g. failed network request or some other error that might occur due to conditions outside of the programmer's control).
To quote from Using Swift with Cocoa and Objective-C:
Although Swift error handling resembles exception handling in Objective-C, it is entirely separate functionality. If an Objective-C method throws an exception during runtime, Swift triggers a runtime error. There is no way to recover from Objective-C exceptions directly in Swift. Any exception handling behavior must be implemented in Objective-C code used by Swift.

error handling in Swift 2

i have to fix the follow code for swift2.
if !UIImagePNGRepresentation(img).writeToFile(imagePath, options: nil, error: &error) {
if let actualError = error {
NSLog("Image not saved. \(actualError)")
}
}
To compile it i have this error on if row: Cannot invoke writeToFile with an argument list of type (String, options: _, error: inout NSError?)
How I can fix it.
Try it with
UIImagePNGRepresentation(img)?.writeToFile(imagePath, atomically: true)
instead. Check the Apple Docs.
Edit:
To answer your question more precisely use the error handling in Swift 2.
do {
try UIImagePNGRepresentation(img)?.writeToFile(imagePath, options: .DataWritingAtomic)
} catch let error as NSError {
print("Image not saved. \(error.description)")
}

Calling checkResourceIsReachableAndReturnError in Swift 2.0

I am having some issues migrating from Swift 1.2 to 2.0 particularly understanding error handling when calling methods from objective-c API. For example, I can't implement the method checkResourceIsReachableAndReturnError correctly. According to the Swift documentation for this method it will return a Bool. I want to check if a folder (self.baseURL) exists and tried the two following approaches:
let folderExists: Bool
do{
try folderExists = self.baseURL!.checkResourceIsReachableAndReturnError(){
} catch let error as NSError {
}
}
And:
let folderExists: Bool
var error: NSError?
do{
try folderExists = self.baseURL!.checkResourceIsReachableAndReturnError(&error){
} catch error as NSError {
}
}
But neither approaches work. I also thought that the Swift implementation of error throwing functions with the word AndReturnError would be shortened to checkResourceIsReachable but that does not seem to be the case.
I am sure I am doing something fundamentally wrong here and if someone has a suggestion for where to look I would appreciate that.
This method indeed returns a bool, it hasn't been modified to follow the new do try catch mechanism of Swift 2: it doesn't throw.
So you just use it like this, without do try catch:
var error:NSError?
let folderExists = self.baseURL!.checkResourceIsReachableAndReturnError(&error)