harry lakins harry lakins - 2 months ago 14
Swift Question

Why is my UIImage not set propely in Swift?

I am using

MKMapSnapShotter
, but when I set a break point on
return finalImage
, I can see the value is just an empty
ObjectiveC.NSObject
, instead of
UIImage
.

func getIMG() -> UIImage{
var finalImage = UIImage();
let imageOptions = MKMapSnapshotOptions();
imageOptions.region = mapView.region;
imageOptions.size = mapView.frame.size;
imageOptions.showsBuildings = true;

let imgMap = MKMapSnapshotter(options: imageOptions);
imgMap.start(completionHandler: { (imageObj: MKMapSnapshot?, Error) -> Void in
if(Error != nil){
print("\(Error)");
}else{
finalImage = imageObj!.image;
}

});

return finalImage;

}


My map loads correctly, etc, so the problem must be here. Also, what is the quickest and easiest way to view the image for testing purposes ? (I don't want to have to design a imageView, etc just to see the image it produces).

Cheers

UPDATE:

func getIMG( completion: @escaping (UIImage)->() ){
var finalImage = UIImage();
let imageOptions = MKMapSnapshotOptions();
imageOptions.region = mapView.region;
imageOptions.size = mapView.frame.size;
imageOptions.showsBuildings = true;

let imgMap = MKMapSnapshotter(options: imageOptions);
imgMap.start(completionHandler: { (imageObj: MKMapSnapshot?, Error) -> Void in
if(Error != nil){
print("\(Error)");
}else{
finalImage = imageObj!.image;
}
completion(finalImage);

});

}


-

map.getMapAsIMG{ (image) in
print(image);
};


Note: compiler needed me to use @escape ...

Answer

You can not return from function that use closure, so you also use closure with your function.

func getIMG(completion: (UIImage) -> ()) {

    var finalImage =  UIImage();
    let imageOptions = MKMapSnapshotOptions();
    imageOptions.region = mapView.region;
    imageOptions.size = mapView.frame.size;
    imageOptions.showsBuildings = true;

    let imgMap = MKMapSnapshotter(options: imageOptions);
    imgMap.start(completionHandler: { (imageObj: MKMapSnapshot?, error) -> Void in
        if(error != nil){
            print("\(Error)");
        }else{
            finalImage = imageObj!.image;
        }
        completion(finalImage)
    });
}

Now call this function like this.

self.getIMG { (image) in
    //Access the image object
}