4

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!

9
  • put a breakpoint at the line where you've got return image. What is it?
    – Adrian
    Oct 24, 2019 at 4:03
  • @Adrian What do you mean?
    – Eli Front
    Oct 24, 2019 at 4:05
  • Have a peek at this: youtube.com/watch?v=mgspBMsWlS4. Type. po image after you've thrown in a breakpoint and see what it is.
    – Adrian
    Oct 24, 2019 at 4:14
  • Also, have a peek at the section struct ImageProvider: RequestImages in this post. medium.com/better-programming/…
    – Adrian
    Oct 24, 2019 at 4:24
  • 2
    I think you should accept the answer and ask another question. You’ve expanded the scope of your original question. TBQH, I haven’t fiddled with SwiftUI much, so I don’t have an authoritative answer there.
    – Adrian
    Oct 24, 2019 at 4:37

3 Answers 3

7

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!

0
3

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)

            }
        }
    }
3
  • I have tried this before, but I had a hard time using the completion result in a SwiftUI view
    – Eli Front
    Oct 24, 2019 at 4:27
  • @EliFront I can't provide exact solution as i didn't use SwiftUI much as of now. But i think you will need some State variable and bind your Image to that and later once you get the UIImage in completion, just set State variable so your Image can update. You can check this link as well.
    – Kamran
    Oct 24, 2019 at 4:43
  • Too bad because I feel like I’m so close. I just need to figure out how to call a function from within a swiftUI view that doesn’t return a view
    – Eli Front
    Oct 24, 2019 at 4:59
1
import SwiftUI

@available(macCatalyst 14.0, *)
@available(iOS 14.0, *)

struct MyUIView : View {
    
    // MARK: - Properties -
    
    @StateObject var myStore : MyStore = MyStore()
    @State var imgArray : Array<Image> = Array<Image>.init(repeating: Image("no-image"), count: 100)

    // MARK: - View -

    var body : some View {
        
        ScrollView {
                                        
            Text("IMAGES")

            LazyVStack (alignment: .leading, spacing: 8.0) {
                
                // actionPlans
                
                ForEach((0 ..< myStore.data.count).clamped(to: 0..<2), id: \.self) { i in
                    
                    HStack {
                        
                        let url = myStore.data[i]
                                       
                        let img : Image = imgArray[i]
                        
                        img
                            .resizable()
                            .scaledToFit()
                            .frame(width: 50, height: 50, alignment: .leading)
                            .padding(EdgeInsets(top: 0, leading: 0.0, bottom: 0, trailing: 16.0))
                            .onAppear(){
                            
                                imageFrom(url: url, completion: { image in
                                                                    
                                    imgArray[i] = Image(uiImage: image!)
                                                                            
                                })
                                
                            }
                                                    
                    }
                    
                    Divider()
                    
                }
                            
            }
                        
        }.onAppear(perform: {
            
            fetch()
            
        })
                
    }
    
    // MARK: - Media -

    private func fetch() {
        
        DispatchQueue.main.async {
            
            myStore.getData()

        }

    }
    
    func imageFrom(url: String, completion: @escaping (UIImage?) -> Void) {
        
        // image
                                
        if ImageLoader.sharedInstance.checkForImage(url: url as NSString?) {
            
            // has image
            
            completion(ImageLoader.sharedInstance.returnImage(url: url as NSString?)!)
            
        } else {
            
            ImageLoader.sharedInstance.getImage(url: url as NSString?) { (image) in
                                    
                if image != nil {
                    
                    completion(image)
                    
                } else {
                    
                    completion(UIImage.init(named: "no-image"))
                    
                }
                            
            }
            
        }
    }
    
}

@available(macCatalyst 14.0, *)
@available(iOS 14.0, *)

struct MyUIView_Previews: PreviewProvider {

    static var previews: some View {
        MyUIView()
    }

}
1
  • I want you to know that your answer here finally made completion handlers click for me. Not sure why it was so hard for me to connect the pieces together but for some reason this example code put them all together. :)
    – zypherman
    Apr 19, 2022 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.