从完成处理程序返回值

编程入门 行业动态 更新时间:2024-10-26 00:19:56
本文介绍了从完成处理程序返回值 - Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在Utilities类中使用了loadImage方法,并且在通过闭包返回图像时遇到了一些麻烦。基本上是因为我的代码可以返回图像或错误,在调用方法时将其分配给图像属性将不起作用。

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 an error, assigning it to an image property when the method is called will not work.

我正在使用的方法在类的方法声明中有错误,或者我应该以不同的方式调用方法来预测可能不同的结果?谢谢

Is the approach I'm using wrong in the method declaration of the class, or should I be calling the method differently to anticipate potentially differing results? Thanks

public class UtilitiesService: NSObject { public class func loadImage(urlString:String) { 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 { self.returnImage(data) } }) } public class func returnImage(imageData: NSData) -> UIImage { return UIImage(data: imageData)! } } //// view controller class someView: UIViewController { var image.image = loadImage(url) ///will throw a return type error }

推荐答案

为 loadImage func添加处理程序:

Add a handler to your loadImage func:

Swift 3

Swift 3

func loadImage(_ urlString: String, handler:@escaping (_ image:UIImage?)-> Void) { let imageURL: URL = URL(string: urlString)! URLSession.shared.dataTask(with: imageURL) { (data, _, _) in if let data = data{ handler(UIImage(data: data)) } }.resume() }

调用func像这样:

loadImage("SomeURL") { (image) -> Void in if let image = image{ DispatchQueue.main.async { self.imageView.image = image } } }

Swift 2.3

Swift 2.3

func loadImage(urlString: String, handler: (image:UIImage?)-> Void) { let imageURL: NSURL = NSURL(string: urlString)! NSURLSession.sharedSession().dataTaskWithURL(imageURL) { (data, _, _) in if let data = data{ handler(image: UIImage(data: data)) } }.resume() }

像这样调用func:

loadImage("someURL") { (image) -> Void in if let image = image{ dispatch_async(dispatch_get_main_queue()) { self.imageView.image = image } } }

更多推荐

从完成处理程序返回值

本文发布于:2023-11-26 03:33:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632469.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:返回值   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!