Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ALAsset in Swift

I know that Swift and Xcode 6 are both still in beta, but I think in my case there is a structural bug that is not related to Swift or Xcode 6 in any way. If the stackoverflow community rates this as an inappropriate question, I can delete it immediately.

But let's get to my question now. I have a UIViewController and I'm trying to add the last image from the camera roll to this view controller (obviously trough an UIImageView). Here is my viewDidLoad method:

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)

    })
}

The problem is that every time I compile the program crashes and Xcode promts me into this nice little file:

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
...
...

The file is long so I'm not posting the entire content here... As you can see it seems to be something related to Swift optionals. That's why I tried to add a ! after every closure variable, for example in the enumerateAssetsAtIndexes method block

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

Some of the elements had the ! before, because in the class reference and in some internet examples I found them (in this case results). Well, after this move the program still crashes, but for another reason... In the

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

line, I get EXT_BAD_ACCESS.

I'm really new to stuff like Assets and I have no Idea why this happens. I followed the example in the Apple AV Foundation programming guide here: https://developer.apple.com/library/mac/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/01_UsingAssets.html I don't know if my change with the ! can help you understand what happened, but I posted it because I think it's an interesting fact that may help. Thank you in advice!

PS: Any help with the code in general is appreciated!

EDIT:

Here is the backtrace:

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

EDIT: With the awesome help of Bill, I modified the code so that the app doesn't crash anymore! Here is the new version:

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)

    })
}

As said, the app doesn't crash anymore, but the image view is not added and the UIViewController is still a white canvas... In my tests, this happens because asset in

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

is nil, and the block never executes... I added the if asset != nil condition because without it the app still crashes. Now, the problem is revealed by Xcode. The backtrace:

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.

So how can I fix this?

like image 965
Philip Müller Avatar asked Nov 01 '22 20:11

Philip Müller


1 Answers

The enumerateGroupsWithTypes can return nil as the group, as specified in the docs. You need to handle the nil case - putting the ! after the group parameter tells Swift to crash the program if you try to use a non-nil group.

To fix:

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

    if group != nil { 
       group.setAssetsFilter(ALAssetsFilter.allPhotos())    
       ...
    }
}
  1. I made group an optional
  2. I check to ensure that group is non-nil.
  3. Instead of using a named usingBlock parameter, I use Swift's support for trailing closures to simply pass a block after the parameter list.
like image 131
Bill Avatar answered Nov 08 '22 08:11

Bill