Skip to content

Commit

Permalink
Resolve concurrency issue in iOS multiple image selection (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
onseok committed Dec 10, 2023
1 parent 467ea46 commit 25d7ea5
Showing 1 changed file with 16 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import platform.PhotosUI.PHPickerViewController
import platform.PhotosUI.PHPickerViewControllerDelegateProtocol
import platform.UIKit.UIApplication
import platform.darwin.NSObject
import platform.darwin.dispatch_group_create
import platform.darwin.dispatch_group_enter
import platform.darwin.dispatch_group_leave
import platform.darwin.dispatch_group_notify
import platform.posix.memcpy

@Composable
Expand All @@ -34,21 +38,30 @@ actual fun rememberImagePickerLauncher(
@Suppress("UNCHECKED_CAST")
val results = didFinishPicking as List<PHPickerResult>

val dispatchGroup = dispatch_group_create()
val imageData = mutableListOf<ByteArray>()

for (result in results) {
dispatch_group_enter(dispatchGroup)
result.itemProvider.loadDataRepresentationForTypeIdentifier(
typeIdentifier = "public.image",
) { nsData, _ ->
scope?.launch(Dispatchers.Main) {
val data = mutableListOf<ByteArray>()
nsData?.let {
val bytes = ByteArray(it.length.toInt())
memcpy(bytes.refTo(0), it.bytes, it.length)
data.add(bytes)
imageData.add(bytes)
}
onResult(data.toList())
dispatch_group_leave(dispatchGroup)
}
}
}

dispatch_group_notify(dispatchGroup, platform.darwin.dispatch_get_main_queue()) {
scope?.launch(Dispatchers.Main) {
onResult(imageData)
}
}
}
}

Expand Down

0 comments on commit 25d7ea5

Please sign in to comment.