Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 等待具有异步操作的函数完成_Swift_Asynchronous_Swift3_Grand Central Dispatch - Fatal编程技术网

Swift 等待具有异步操作的函数完成

Swift 等待具有异步操作的函数完成,swift,asynchronous,swift3,grand-central-dispatch,Swift,Asynchronous,Swift3,Grand Central Dispatch,我如何等待一个本身具有异步操作的函数完成 让我举个例子: 功能\u A从多媒体资料中获取照片。取数操作将使用取数闭包异步执行 我在Function\u B中调用Function\u A,希望等待照片获取操作完成,然后继续我的代码 我所尝试的: 我使用过调度组,但它不起作用。我还尝试在同步块中调用函数A,但也没有成功 如何等待此操作完成?此问题是否可能是因为正在将抓取操作运行到另一个队列 更新: 这就是我所做的: class imageFetch: NSObject{ var theIma

我如何等待一个本身具有异步操作的函数完成

让我举个例子:

功能\u A
从多媒体资料中获取照片。取数操作将使用取数闭包异步执行

我在
Function\u B
中调用
Function\u A
,希望等待照片获取操作完成,然后继续我的代码

我所尝试的:

我使用过调度组,但它不起作用。我还尝试在同步块中调用
函数A
,但也没有成功

如何等待此操作完成?此问题是否可能是因为正在将抓取操作运行到另一个队列

更新

这就是我所做的:

class imageFetch: NSObject{
    var theImage: PHAsset? = nil
    func Function_A(){
        let fetchOption = PHFetchOptions()         
        PHPhotoLibrary.requestAuthorization { (authStatus) in
            // It seems code will be executed asynchronously from here
            if authStatus == .authorized{
                let imageAsset = PHAsset.fetchAssets(with: .image, options: fetchOption)
            // Select image and save it in theImage
            // I know I can send a closure and run it here
            }
        }
    }
}
在另一个类中,我称之为函数:

class edit: NSObject{
    funct Function_B(){
        var imageFetchIns = imageFetch()
        // I want below code to execute asynchronously
        imageFetchIns.Function_A()

        // Now I want to wait last operation to finish
    }
}

没有代码是很难理解发生了什么。如果你看一看,你会发现发生了什么事

否则,您可以开始使用
NSOperation
NSOperationQueue
。事实上,如果有两个操作,可以在它们之间添加依赖项。换句话说,您可以说一个操作只有在它所依赖的操作完成后才能启动。除此之外,操作还具有可取消的好处。例如,在处理用户操作时非常有用。 将给你一个很好的介绍如何使用它们


我想在操作中强调的是,操作(特别是当您将其子类化时)代表一个可以在您的项目中或在不同的项目中重用的自包含任务。

您查看过promise库吗?不确定dispatchgroup为什么不能工作。试着用它来显示代码。RxSwift也会很容易地解决这个任务。是
PHAsset
你的代码吗?我用PHAsset来存储我选择的图像。这不是我的问题。问题是我在代码中的注释是
等待最后一个操作完成