var input = AVCaptureDeviceInput(device: backCamera)
The error message i get says call can throw, but it is not marked with 'try' and the error is not handled.
also I have this line of code
if ((error == nil && captureSession?.canAddInput(input)) != nil)
Optional type 'Bool' cannot be used as a boolean; test for "!=nil" instead.
Auto Correct is on but for the second line when i click fix it just rewrites the same line of code and adds another "!=nil".
You are getting the error that says
this call can throw, but it is not marked with try and the error is not handled.
because you did not catch the exceptions that could be thrown. Instead, you should be using this
var error: NSError?
do{
let input = try AVCaptureDeviceInput(device: backCamera)
}
catch let myError as NSError{
error = myError
}
The second error is because captureSession?.canAddInput(input) returns an optional Bool value. To fix this, you should be using (captureSession?.canAddInput(input) ?? false), which effectively turns nil values into false.
if(error == nil && (captureSession?.canAddInput(input) ?? false))
A better way to do this would be to put it all in the do-catch statement
do{
let input = try AVCaptureDeviceInput(device: backCamera)
if((captureSession?.canAddInput(input) ?? false)){
//your code
}
}
catch var error as NSError{
//handle the NSError 'error'
}
For your first line, I believe all you have to do is surround it with a
do{
try //statement
}catch {
}
For the second statement, I believe the reason why the compiler is complaining is because you are trying to evaluate a type Bool for nil or not, try simply having
(error == nil && captureSession?.canAddInput(input))
Related
My iOS app stops running after a run-time error occurs. I'm catching the error as an exception. I would like the app to continue running to the next steps after error handling. Any advises how to do this?
do {
guard let ps: Element = try! docu.getElementById("product-name")! else { ide = "" }
if ps != nil {
ide = (try ps.text())
}
} catch {
print("error")
ide = ""
}
I think you are overusing the ! (force unwrap) symbol here. It does not deal gracefully with nil values, in fact, it crashes.
I think what you might want to be doing here is
guard
let ps: Element = try? doc.getElementById("product-name"),
let ide = try? ps.text()
else {
print("error")
ide = ""
}
// ide is guaranteed to be valid here
...
Note how if you use try? you do not need to "catch" the error, it will simply return an optional value, nil if the call would raise an exception.
Alternatively you could simply
let ps: Element = try? doc.getElementById("product-name")
let ide = try? ps?.text()
// ide will be an optional value here
If you really don't want to guard/if let...
I used this method very much in Swift 1.2: NSURLConnection.sendSynchronousRequest(:_:_:_) but this is apparently deprecated in iOS9. It still works however but now it uses the new Swift 2.0 Error Handling and I don't know how I will get the error message if it fails, ex. if time runs out.
I know I have to put it into a do-catch and then say try before the metho but I dont know how to catch the error message.
do {
let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
return data
}
catch _ {
return nil
}
Before I used NSError and then its description property, but now I have no clue.
Use automatic error variable, and you can cast it to NSError if you wish:
catch {
let nsError = error as NSError
print(nsError.localizedDescription)
}
You can now throw any object inheriting ErrorType, and provide custom handling in the catch sentence. You can also cast the error to NSError to access localizedDescription for handling third party errors.
Casting an enum ErrorType will produce a NSError with domain equal to the enum name, code equal to the enum value and an auto-generated localizedDescription with the following format:
The operation couldn’t be completed. (DOMAIN error CODE.)
For example, the following code:
enum AwfulError: ErrorType {
case Bad
case Worse
case Terrible
}
func throwingFunction() throws {
throw AwfulError.Worse
}
do {
try throwingFunction()
}
catch AwfulError.Bad {
print("Bad error")
}
catch let error as NSError {
print(error.localizedDescription)
}
Will print
The operation couldn’t be completed. (AwfulError error 1.)
Despite the question title specifying Swift 2, this answer is for Swift 3.
As #redent84 points out, since Swift 2 an Error object may be a home-made one. Here's a method I wrote to analyze and print the default error object available in a "catch" statement that doesn't specify any specific error type:
// Method to print an unknown Error type object to the system output.
static func printCaughtError(_ unknownError : Error) {
let objectDescription = String(describing: unknownError)
let localizedDescription = unknownError.localizedDescription
if localizedDescription != "" {
if localizedDescription.contains(objectDescription) {
print(localizedDescription)
return
}
if !objectDescription.contains(localizedDescription) {
print(objectDescription + ": " + localizedDescription)
return
}
}
print(objectDescription)
}
Then you can call it like this:
catch {
printCaughtError(error)
}
How to get the error message that is inside userInfo:
let errorMessage = (error as NSError).userInfo["message"] as? String
I am following this from code in an old swift tutorial so possibly there was a change I was unaware of in Swift 2 with how to handle errors, but here is my code
backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var error : NSError?
var input = AVCaptureDeviceInput(device: backCamera, error: &error)
I do not understand as to why the error in the title even occurs, it occurs highlighting the input variable.
That is deprecated. Use this:
var input = AVCaptureDeviceInput()
do {
input = try AVCaptureDeviceInput(backCamera)
} catch {
//error
}
Check some Swift 2 documentation. The constructor is defined with a single device: parameter and a throws annotation instead of the error:.
Update swift3
This is how we can handle AVCaptureDeviceInput error on swift3
var input = AVCaptureDeviceInput()
do {
input = try AVCaptureDeviceInput(device: device)
}
catch {
// error
}
Using Xcode 7 and swift 2.0 if get the following error on the context?.save(nil).
Any help is appreciated
"cannot use optional chaining on non-optional value of type 'NSManagedObjectContext'
func newItem() {
let context = self.context
let ent = NSEntityDescription.entityForName("CallList", inManagedObjectContext: context)
let nItem = CallList(entity: ent!, insertIntoManagedObjectContext: context)
nItem.firstname = firstName.text
nItem.lastname = lastName.text
nItem.phonenumber = phoneNumber.text
context?.save(nil)
You get that error as your context variable is not optional so the ? is useless.
Also swift 2 introduced the do-catch construct to allow advanced error handling as you would do in other languages with try-catch, so functions with an error parameter such as save() of NSManagedObjectContext changed and have lost the error parameter and report errors as exceptions; so you should do
do {
try context.save()
} catch let error {
// Handle error stored in *error* here
}
If you don't want to handle the error you can do
do {
try context.save()
} catch {}
I used this method very much in Swift 1.2: NSURLConnection.sendSynchronousRequest(:_:_:_) but this is apparently deprecated in iOS9. It still works however but now it uses the new Swift 2.0 Error Handling and I don't know how I will get the error message if it fails, ex. if time runs out.
I know I have to put it into a do-catch and then say try before the metho but I dont know how to catch the error message.
do {
let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
return data
}
catch _ {
return nil
}
Before I used NSError and then its description property, but now I have no clue.
Use automatic error variable, and you can cast it to NSError if you wish:
catch {
let nsError = error as NSError
print(nsError.localizedDescription)
}
You can now throw any object inheriting ErrorType, and provide custom handling in the catch sentence. You can also cast the error to NSError to access localizedDescription for handling third party errors.
Casting an enum ErrorType will produce a NSError with domain equal to the enum name, code equal to the enum value and an auto-generated localizedDescription with the following format:
The operation couldn’t be completed. (DOMAIN error CODE.)
For example, the following code:
enum AwfulError: ErrorType {
case Bad
case Worse
case Terrible
}
func throwingFunction() throws {
throw AwfulError.Worse
}
do {
try throwingFunction()
}
catch AwfulError.Bad {
print("Bad error")
}
catch let error as NSError {
print(error.localizedDescription)
}
Will print
The operation couldn’t be completed. (AwfulError error 1.)
Despite the question title specifying Swift 2, this answer is for Swift 3.
As #redent84 points out, since Swift 2 an Error object may be a home-made one. Here's a method I wrote to analyze and print the default error object available in a "catch" statement that doesn't specify any specific error type:
// Method to print an unknown Error type object to the system output.
static func printCaughtError(_ unknownError : Error) {
let objectDescription = String(describing: unknownError)
let localizedDescription = unknownError.localizedDescription
if localizedDescription != "" {
if localizedDescription.contains(objectDescription) {
print(localizedDescription)
return
}
if !objectDescription.contains(localizedDescription) {
print(objectDescription + ": " + localizedDescription)
return
}
}
print(objectDescription)
}
Then you can call it like this:
catch {
printCaughtError(error)
}
How to get the error message that is inside userInfo:
let errorMessage = (error as NSError).userInfo["message"] as? String