Return value from completion handler - Swift

后端 未结 2 1334
日久生厌
日久生厌 2020-12-01 17:04

I\'m using a loadImage method in a Utilities class and am having some trouble with returning images via closures. Basically because my code could return either an image or a

2条回答
  •  被撕碎了的回忆
    2020-12-01 17:34

    I would do it this way:

    public class UtilitiesService: NSObject {
        public class func loadImage(urlString:String, completion:(resultImage:UIImage) -> Void)
        {
    
        var imgURL: NSURL = NSURL(string: urlString)!
        let request: NSURLRequest = NSURLRequest(URL: imgURL)
        NSURLConnection.sendAsynchronousRequest(
            request, queue: NSOperationQueue.mainQueue(),
            completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
                if error == nil {
                    completion(resultImage: UIImage(data: data))
                }
        })
    }
    }
    
    //// view controller
    class someView: UIViewController {
    var image: UIImageView()? //Create the variable the way you need
    loadImage(url, completion: { (resultImage) -> Void in
        image = resultImage //Assign the result to the variable
    })
     }
    

    I think this will work, if it doesn't, tell me and I'll fix it

提交回复
热议问题