ios - 如何从完成处理程序 iOS Swift 3 获取值

标签 ios swift swift3 closures

有人可以建议或指导,我怎样才能在下面的代码中返回在 Location 1 获得的 ProfileImage 并在 Location 2。非常感谢您的帮助。我已经解决了其他 SO 问题,但没有一个对我有帮助。

static var profileImage : UIImage{

    get{
        let defaults        = UserDefaults.standard

        guard let imageData = defaults.object(forKey: "profileImage") as? NSData else{
            downloadAndSetProfileImage(completionHandler: { (profileImage) in

               // LOCATION 1:
               // PLEASE ADVISE HOW I CAN RETURN THE OBTAINED PROFILE IMAGE BELOW at LOCATION 2
            })

        }

        // LOCATION 2:
        // I would like to return the profileImage Here i.e. return profileImage

    }
    set (image){

        let defaults        = UserDefaults.standard
        let imageData : NSData = UIImagePNGRepresentation(image)! as NSData
        defaults.set(imageData, forKey: "profileImage")
    }
}

最佳答案

您不应该将异步任务放入您的 getter 中。相反,您可以使用可选的 profileImage 计算属性仅从用户默认值获取图像,并创建另一个异步函数来获取用户配置文件,如果它不是零,它将从默认值返回图像,否则它它会尝试下载一个吗?像这样:

static var profileImage : UIImage? {
    get {
        let defaults = UserDefaults.standard
        guard let imageData = defaults.object(forKey: "profileImage") as? NSData else {
            return nil
        }
        return UIImage(data: Data(referencing: imageData))
    }
    set {
        let defaults = UserDefaults.standard
        guard newValue != nil else {
            defaults.removeObject(forKey: "profileImage")
            return
        }
        let imageData = NSData(data: UIImagePNGRepresentation(newValue!)!)
        defaults.set(imageData, forKey: "profileImage")
    }
}

// Async function to retrieve profile image
func getProfileImage(completion: (_ image: UIImage?) -> ()) {
    guard ProfileAPI.profileImage == nil else {
        completion(ViewController.profileImage!)
        return
    }

    // Your image dowload funciton
    SomeImageDownloader.downloadImage("imagePath") { downloadedImage in
        completion(downloadedImage) // assuming downloadedImage can be nil
    }
}

要获取您的个人资料图片,请调用:

getProfileImage { (image) in
    if let profileIage = image {
        // do something with it
    }
}

在示例中,getProfileImageprofileImage 属性与 downloadImage 组合在一起。如果 getProfileImage 有一个值,它将立即通过完成闭包传递它,否则它将调用 downloadImage 并在任务结束时传递结果。归根结底,您遇到了需要异步任务的情况,因此您需要某种完成处理程序,例如我的示例中的完成处理程序。

关于ios - 如何从完成处理程序 iOS Swift 3 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46987247/

相关文章:

swift - 我们如何在其选择项委托(delegate)上重新加载 Collection View ?

ios - 如何调整正在打印在另一个图像上的图像的大小(swift3)

iphone - iPad 上的应用程序存储有任何限制吗?

ios - 杀死或中断 dispatch_queue_t 方法

ios - AVMutableCompositionTrack 和 AVMutableVideoComposition 问题中没有视频的范围

ios - JSON 文本未以数组或对象开头,并且未设置允许片段的选项

ios - 在 Swift 2.0 中定义 'UITableViewCell' 变量

swift - 具有多个输入和多个输出的游戏 AI 的 CoreML

swift - 根据摩擦和张力确定 springWithDamping 和 initialSpringVelocity

swift - Swift 3 中与 Cocoa 的线程间对象通信