我在Utilities类中使用loadImage方法,并且在通过闭包返回图像时遇到了一些麻烦。基本上因为我的代码可能返回图像或错误,所以在调用该方法时将其分配给image属性是行不通的。
我在类的方法声明中使用的方法是否错误,还是应该以不同的方式调用该方法以预期潜在的不同结果?谢谢
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 函数中:
迅捷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 } } }
斯威夫特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() }
loadImage("someURL") { (image) -> Void in if let image = image{ dispatch_async(dispatch_get_main_queue()) { self.imageView.image = image } } }