2017-01-23 1 views
0

저는 현재 AVFoundation 프레임 워크를 사용하여 사용자 정의 카메라보기를 만드는 방법을 보여주는 자습서를 따르고 있습니다.do 블록 내의 AVCaptureDeviceInput

AVCaptureDeviceInput의 인스턴스를 인스턴스화 할 때 약간의 혼란을 겪고 있습니다.

나는 다음과 같습니다

var error: NSError? 

     do { 
      let input = try AVCaptureDeviceInput(device: backCamera) as AVCaptureDeviceInput 
      if error == nil && captureSession!.canAddInput(input) { 
       captureSession!.addInput(input) 
      } 
     } catch error { 
      // Handle errors 
     } catch { 
      // Catch other errors 
     } 

내가 직면하고 오류입니다 :

이 인수 유형 'NSError가'예상 tpye '_ErrorCodeProtocol'

을 준수하지 않는 이 문제를 해결하기 위해 캐치에 다음을 추가했습니다.

catch error as! NSError 

이 오류는 컴파일 오류를 수정 했음에도 불구하고이 작업을 수행하면 오류 확인 변수가 다시 지정되지 않으므로 if 체크를 무의미하게 만들 수 있습니까?

저는 Swift 프로그래밍 언어에 비교적 익숙하므로 어떤 도움을 주시면 대단히 감사하겠습니다.

미리 감사드립니다.

답변

1

스위프트에서 do-try-catch을 사용할 때 보통 error 변수를 선언 할 필요가 없습니다. 당신은 구문 같은 case-let를 사용하여 오류를 catch 수 있습니다 : 당신이 그렇게 } catch let error {로 라인을 쓰기는 catch 조항의 일부를 생략하거나 } catch { 해당하는 경우

//### Usually, no need to declare `error`. 
do { 
    let input = try AVCaptureDeviceInput(device: backCamera) as AVCaptureDeviceInput 
    //### When error occures, the rest of the code in do-catch will not be executed, you have no need to check `error`. 
    if captureSession!.canAddInput(input) { 
     captureSession!.addInput(input) 
    } 
} catch let error as Error { 
    // Handle all errors 
    print(error) 
    //... 
} //### The `catch` above catches all errors, no need to put another `catch` 

스위프트가 자동으로 let error as Error 가정합니다.

+0

아, 설명해 주셔서 감사합니다. 훨씬 더 의미가 있습니다. 감사 :) –

관련 문제