2014-07-13 8 views
5

스위프트와 Xcode 6은 모두 베타 버전이지만, 제 경우에는 스위프트 또는 Xcode 6과 관련이없는 구조적인 버그가 있다고 생각합니다. stackoverflow 커뮤니티에서이 질문을 부적절한 질문으로 평가하면 즉시 삭제할 수 있습니다.스위프트에서 ALAsset 사용하기

하지만 이제 내 질문에 대해 알아 보겠습니다. UIViewController 있고이 뷰 컨트롤러 (분명히 물마루 UIImageView) 카메라 롤에서 마지막 이미지를 추가하려면 노력하고있어. 여기 내 viewDidLoad에 방법입니다 :

override func viewDidLoad() { 
    super.viewDidLoad() 

    var assetLib = ALAssetsLibrary() 

    var url: NSURL = NSURL() 

    var imageView = UIImageView(frame: self.view.bounds) 

    assetLib.enumerateGroupsWithTypes(ALAssetsGroupType(ALAssetsGroupSavedPhotos), usingBlock: { 
    (group: ALAssetsGroup!, stop: CMutablePointer<ObjCBool>) in 

    group.setAssetsFilter(ALAssetsFilter.allPhotos()) 

    group.enumerateAssetsAtIndexes(NSIndexSet(index: group.numberOfAssets()-1), options: nil, usingBlock: { 
     (result: ALAsset!, index: Int, stop: CMutablePointer<ObjCBool>) in 
     if result { 
     var alAssetRapresentation: ALAssetRepresentation = result.defaultRepresentation() 
     url = alAssetRapresentation.url() 

     if group == nil { 

      assetLib.assetForURL(url, resultBlock: { 
      (asset: ALAsset!) in 

      var assetRep: ALAssetRepresentation = asset.defaultRepresentation() 
      var iref = assetRep.fullResolutionImage().takeUnretainedValue() 
      var image = UIImage(CGImage: iref) 

      imageView.image = image 

      self.view.addSubview(imageView) 

      }, failureBlock: { 
       (error: NSError!) in 

       NSLog("Error!", nil) 
      }) 
     } 
     } 
     }) 
    }, failureBlock: { 
     (error: NSError!) in 

     NSLog("Error!", nil) 

    }) 
} 

문제는 때마다 나는이 프로그램이 충돌을 컴파일하고 엑스 코드이 좋은 작은 파일로 저를 칠때이다 :

IdealityS`Swift._getOptionalValue <A>(Swift.Optional<A>) -> A: 
0x6540: pushl %ebp 
0x6541: movl %esp, %ebp 
0x6543: pushl %ebx 
0x6544: pushl %edi 
0x6545: pushl %esi 
0x6546: subl $0x8c, %esp 
0x654c: calll 0x6551     ; Swift._getOptionalValue <A> (Swift.Optional<A>) -> A + 17 
... 
... 

파일은 내가 아니에요 긴 여기에 전체 내용을 게시 ... 볼 수 있듯이 Swift 선택 사항과 관련된 것으로 보입니다. 그게 내가 왜! 모든 클로저 변수 다음에, 예를 들어 enumerateAssetsAtIndexes 메서드 블록에서

{(result: ALAsset!, index: Int!, stop: CMutablePointer<ObjCBool>!) in 
... 
} 

일부 요소는! 클래스 참조 및 일부 인터넷 예제에서 (이 경우 결과) 찾을 수 있기 때문에 전에. 음,이 후

group.enumerateAssetsAtIndexes(NSIndexSet(index: group.numberOfAssets()-1), options: nil, usingBlock: { 

라인에서 ... 프로그램이 계속 충돌 이동하지만, 또 다른 이유로, 나는 EXT_BAD_ACCESS를 얻을.

저는 자산과 같은 물건을 처음 접했고 아이디어가 없습니다. 이유는 무엇입니까? 나는 Apple AV Foundation 프로그래밍 가이드의 예제를 다음과 같이 따랐다 : https://developer.apple.com/library/mac/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/01_UsingAssets.html! 무슨 일이 있었는지 이해할 수 있도록 도울 수는 있지만 도움이 될만한 흥미로운 사실이라고 생각하기 때문에 게시했습니다. 조언 해 주셔서 감사합니다.

추신 : 일반적으로 코드에 대한 도움을 주시면 감사하겠습니다.

편집 : 여기

는 역 추적입니다 : 응용 프로그램이 더 이상 충돌하지 않도록 빌의 멋진 도움으로 , 내가 코드를 수정 : 편집

Attempt to add read-only file at path file:///var/mobile/Media/PhotoData/Photos.sqlite?readonly_shm=1 read/write. Adding it read-only instead. This will be a hard error in the future; you must specify the NSReadOnlyPersistentStoreOption. fatal error: Can't unwrap Optional.None

! 여기에 새로운 버전입니다 :

이 같이 말했다
override func viewDidLoad() { 
    super.viewDidLoad() 

    var assetLib = ALAssetsLibrary() 
    var url: NSURL = NSURL() 

    var imageView = UIImageView(frame: self.view.bounds) 

    assetLib.enumerateGroupsWithTypes(ALAssetsGroupType(ALAssetsGroupSavedPhotos), usingBlock: { 
    (group: ALAssetsGroup?, stop: CMutablePointer<ObjCBool>) in 
    if group != nil { 
    group!.setAssetsFilter(ALAssetsFilter.allPhotos()) 
    group!.enumerateAssetsAtIndexes(NSIndexSet(index: group!.numberOfAssets()-1), options: nil, usingBlock: { 
     (result: ALAsset!, index: Int, stop: CMutablePointer<ObjCBool>) in 
     if result { 
     var alAssetRapresentation: ALAssetRepresentation = result.defaultRepresentation() 
     url = alAssetRapresentation.url() 
     } 
     }) 
    } 
    else if group == nil { 

     assetLib.assetForURL(url, resultBlock: { 
     (asset: ALAsset!) in 
     if asset != nil { 
     var assetRep: ALAssetRepresentation = asset.defaultRepresentation() 
     var iref = assetRep.fullResolutionImage().takeUnretainedValue() 
     var image = UIImage(CGImage: iref) 

     imageView.image = image 


     self.view.addSubview(imageView) 

     } 
     }, failureBlock: { 
      (error: NSError!) in 

      NSLog("Error!", nil) 
     }) 
    } 

    }, failureBlock: { 
     (error: NSError!) in 

     NSLog("Error!", nil) 

    }) 
} 

앱이 더 이상 충돌하지 않습니다,하지만 이미지보기가 추가되지 않고있는 UIViewController 내 테스트에서 ... 여전히 흰색 캔버스,이 자산 때문에 발생

assetLib.assetForURL(url, resultBlock: { 
(asset: ALAsset!) in 
if asset != nil { 
... 
} 
} 

은 전무하고, 블록은 결코하지 않고 응용 프로그램이 여전히 충돌 때문에이 경우 자산! = 전무 조건을 추가 ... 실행되지 않습니다. 이제 문제는 Xcode에서 드러납니다. 백 트레이스 :

어떻게 해결할 수 있습니까?

+0

왜'group.enumerateAssetsAtIndexes (NSIndexSet (지수 : group.numberOfAssets() - 1) ...'대신에 단지'self.group.enumerateAssetsUsingBlock (' – Bill

+0

내가 튜토리얼을 따라 말했듯이 내가 (잘 모르겠어요?) 그러나 나는 그것이 마지막 사진에만 접근하고 그들 모두를 열거하기를 원하기 때문에 그것이라고 생각한다 ... –

+0

오류가 발생할 때 백 트레이스를 게시 할 수 있습니까? – Bill

답변

2

enumerateGroupsWithTypes은 문서에 지정된대로 nil을 그룹으로 반환 할 수 있습니다.nil 케이스를 처리해야합니다. 그룹 매개 변수가 0이 아닌 그룹을 사용하려고 시도 할 때 Swift가 프로그램을 중단하도록 지시 한 후에 !을 입력해야합니다.

를 해결하려면 :

assetLib.enumerateGroupsWithTypes(ALAssetsGroupType(ALAssetsGroupSavedPhotos)) { 
    (group: ALAssetsGroup?, stop: CMutablePointer<ObjCBool>) in 

    if group != nil { 
     group.setAssetsFilter(ALAssetsFilter.allPhotos())  
     ... 
    } 
} 
  1. 나는 group 만든 옵션
  2. 내가 group가 nil이 아닌 것을 확인하기 위해 확인.
  3. 매개 변수 목록 뒤에 블록을 전달하기 위해 명명 된 usingBlock 매개 변수를 사용하는 대신 Swift의 후행 클로저에 대한 지원을 사용합니다.
+0

답변 해 주셔서 감사합니다! 하지만 코드를 수정하는 데 도움이 필요합니다 ... 나는 여전히 오류가 발생하기 때문에 내가 올바르게했는지 확신 할 수 없습니다. 곧 "새로운"오류가 포함 된 코드의 새 버전을 게시 할 것입니다. –

0

XCode 6 베타 3에서 문제가 해결 된 것 같습니다. 필자는 사진 라이브러리에서 자산을 올바르게 반복하여 표시 할 수있었습니다. 그러나 ALAssetsGroup 및 ALAsset 모두에 대해 null을 필터링해야하므로 양쪽 매개 변수가 어디에 선언 되었습니까? 대신에 !.