I'm using the following code to iterate through eh albums and if it finds the one I need, it should stop further looping.
public func importPhotosFromGallery(albumName: String = "Last Imported") {
fetchAlbum(albumName) { album, error in
if let error = error {
print("Error occurred fetching album: \(error.localizedDescription)")
} else {
if let album = album {
print("found it! \(album.name)")
}
}
}
}
private func fetchAlbum(albumName: String, completion: (album: ALAssetsGroup?, error: NSError?) -> ()) {
assetsLibrary.enumerateGroupsWithTypes(ALAssetsGroupAlbum, usingBlock: { group, stop in
if group != nil {
group.setAssetsFilter(ALAssetsFilter.allPhotos())
print("group name: \(group.name)")
if group.name == albumName {
stop.initialize(true)
completion(album: group, error: nil)
}
} else {
let notFoundError = NSError.createError("Album Not Found")
completion(album: nil, error: notFoundError)
}
}) { error in
completion(album: nil, error: error)
}
}
I'm changing the stop
variable's value to true
after finding the match but it still executes the else block that returns the notFoundError
at the end. This is the output of the print
statements.
group name: Last Imported
found it! Last Imported
Error occurred fetching album: Album Not Found
How do I stop this from happening?
The docs for enumerationBlock
state
The block to invoke using each asset group in turn.
When the enumeration is done, enumerationBlock is invoked with group set to nil.
That would mean after setting stop
to true the enumerationBlock
is invoked once more, this time with group
being nil and therefore causing the completion(album: nil, error: notFoundError)
-branch to be entered.
That results in your completion block getting called twice, once with the correctly found album and once again at the end of the enumeration.
Try inserting a few print
-statements to see when which branch is entered and what the input is. In particular wether or not the stop
is already set to true
.