Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a completion handler to put an image in a SwiftUI view

I have tried this, but I didn't know how to use the results in a SwiftUI View:

func getProfilePicture(_ completion: @escaping ((UIImage) -> Void)) {

    Alamofire.request(GIDSignIn.sharedInstance()?.currentUser.profile.imageURL(withDimension: 75) ?? "https://httpbin.org/image/png").responseImage { response in

        if let image = response.result.value {
            completion(image)

        }
    }
}

If you can help, I would like to put the returned image from the completion handler in this view:

struct ProfileView: View {
let profileInfo = ProfileInfo()
var placeHolderImage = Image(systemName: "person")

var body: some View {
    Group {
            placeHolderImage
                .clipShape(Circle())
                .overlay(
                    Circle().stroke(Color.white, lineWidth: 4))
                .shadow(radius: 10)
                .padding(10)
    }

}

}

I would like this to return a UIImage so I can eventually use it in a SwiftUI view. I have already tried using a method with an @escaping completion handler, but I couldn't figure out how to use it to fix the issue. Thanks!

like image 598
Eli Front Avatar asked Jan 26 '23 16:01

Eli Front


2 Answers

You can try something let this:

struct ProfileView: View {
    @State var placeHolderImage = Image(systemName: "person")


    var body: some View {
        Group {
            placeHolderImage
                .clipShape(Circle())
                .overlay(
                    Circle().stroke(Color.white, lineWidth: 4))
                .shadow(radius: 10)
                .padding(10)
        }.onAppear{
            getProfilePicture{ image in
                self.placeHolderImage = Image(uiImage: image)
            }
        }

    }

}

When ProfileView appears it will call getProfilePicture. The image specified in image in (when calling the function) is what the completion handler passes through (completion(image)). What you can then do is change your placeHolderImage to what you get in getProfilePicture, but before you do that you need to make your uiImage into an Image. Also make sure you add the @State keyword to your variable so once it changes your View is updated.

Hope that helps!

like image 190
39fredy Avatar answered Jan 30 '23 02:01

39fredy


Use a completion handler as below,

func getProfilePicture(_ completion: @escaping ((UIImage) -> Void)) {

        Alamofire.request(GIDSignIn.sharedInstance()?.currentUser.profile.imageURL(withDimension: 75) ?? "https://httpbin.org/image/png").responseImage { response in

            if let image = response.result.value {
                completion(image)

            }
        }
    }
like image 31
Kamran Avatar answered Jan 30 '23 02:01

Kamran