从完成处理程序返回值 – Swift
我在一个实用工具类中使用loadImage方法,并通过闭包返回图像时遇到一些麻烦。 基本上,因为我的代码可能会返回一个图像或错误,调用方法时将其分配给图像属性将无法正常工作。
我在方法声明中使用的方法是错误的,还是应该以不同的方式调用方法来预测潜在的不同结果? 谢谢
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:
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
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 } } }
我会这样做:
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 }) }
我认为这将起作用,如果没有,告诉我,我会解决它