IOS使用SDWebImage从URL加载图像

我尝试从下面的json URL加载图像,但我得到了[cell.imageView setImageWithURL:[NSURL URLWithString:@"coffeemugDirectLink"] placeholderImage:[UIImage imageNamed:@"heart.png"]]; 错误是Expected ',' separatorExpected expression in container literal我做错了什么? 我怎样才能从JSON加载到UICollectionView我的单元格的URL?

 import UIKit import SDWebImage class TopratedVC: BaseViewController { @IBOutlet var collectionview: UICollectionView! @IBOutlet var Image: UIImageView! //Our web service url let URL_GET_coffeemugs:String = "http://coffeemugs.com/ios/feed.php" override func viewDidLoad() { super.viewDidLoad() addSlideMenuButton() // Do any additional setup after loading the view. //SDWebimage stuff let imageView = UIImageView() //created NSURL let requestURL = NSURL(string: URL_GET_coffeemugs) //creating NSMutableURLRequest let request = NSMutableURLRequest(URL: requestURL!) //setting the method to post request.HTTPMethod = "GET" //creating a task to send the post request let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in //exiting if there is some error if error != nil{ print("error is \(error)") return; } //parsing the response do { guard let coffeemugs = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray else { //Doesn't exist, or isn't an NSArray return } for coffeemug in coffeemugs { //getting the data at each index let coffeemugName = coffeemug["name"] as! String let coffeemugDirectLink = coffeemug["direct_link"] as! String let coffeemugImage = coffeemug["image"] as! String //displaying the data print("name -> ", coffeemugName) print("direct_link -> ", coffeemugDirectLink) print("image -> ", coffeemugImage) print("===================") print() } } catch { print(error) } } // Make cell func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) [cell.imageView setImageWithURL:[NSURL URLWithString:@"coffeemugDirectLink"] placeholderImage:[UIImage imageNamed:@"heart.png"]]; return cell } //executing the task task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 

你的代码有几个问题。 你所问的是由于将某些Objective-C语法转储到Swift程序的中间而造成的,但是更大的问题是,你不能将你从API中检索到的数据存储在你的cellForItemAtIndexPath可以获取的任何地方。

此外, cellForItemAtIndexPath需要是您的视图控制器类的实例方法,它可以根据需要由UICollectionView调用。 你不能把它作为一个内联函数,并希望它能工作。

你需要创build一个数组来存储你的马克杯和一个结构放入数组中。

 struct Mug { var name: String var directLink: String var image: String } import UIKit import SDWebImage class TopratedVC: BaseViewController, UICollectionViewDataSource { @IBOutlet var collectionview: UICollectionView! @IBOutlet var Image: UIImageView! var mugs = [Mug]() var placeholderImage = UIImage(named:"heart.jpg")! //Our web service url let URL_GET_coffeemugs = "http://coffeemugs.com/ios/feed.php" override func viewDidLoad() { super.viewDidLoad() // addSlideMenuButton() // Do any additional setup after loading the view. //created NSURL if let requestURL = NSURL(string: URL_GET_coffeemugs) { //creating NSMutableURLRequest let request = NSMutableURLRequest(URL: requestURL) //setting the method to post request.HTTPMethod = "GET" //creating a task to send the post request let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in //exiting if there is some error if error != nil{ print("error is \(error)") return; } //parsing the response do { guard let coffeemugs = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray else { //Doesn't exist, or isn't an NSArray return } var newMugs=[Mug]() for coffeemug in coffeemugs { //getting the data at each index let coffeemugName = coffeemug["name"] as! String let coffeemugDirectLink = coffeemug["direct_link"] as! String let coffeemugImage = coffeemug["image"] as! String let newMug = Mug(name:coffeemugName, directLink: coffeemugDirectLink, image:coffeemugImage) newMugs.append(newMug) //displaying the data print("name -> ", coffeemugName) print("direct_link -> ", coffeemugDirectLink) print("image -> ", coffeemugImage) print("===================") print() } dispatch_async(dispatch_get_main_queue(),{ self.mugs = newMugs self.collectionview.reloadData() }) } catch { print(error) } } //executing the task task.resume() } } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.mugs.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) let mug = self.mugs[indexPath.item] if let imageURL = NSURL(string:mug.image) { cell.imageView.setImageWithURL(imageURL,placeholderImage:self.placeholderImage) } else { cell.imageView.image = self.placeholderImage } return cell } } 

一些纯粹主义者可能会抱怨我的占位符图像的力量解开,但老实说,如果失败了,你的应用程序资源中有一些乱七八糟的东西,崩溃会在开发时告诉你。

那一行:

  [cell.imageView setImageWithURL:[NSURL URLWithString:@"coffeemugDirectLink"] placeholderImage:[UIImage imageNamed:@"heart.png"]]; 

在你的Swift程序中间是Objective-C代码。 这是行不通的。 您将需要将该代码转换为Swift。

我也不认识你想要使用的方法, setImageWithURL:placehodlerImage: 你是否使用了一些UIImageView自定义子类? 如果是这样,你需要告诉我们关于这个子类,并告诉我们该函数的定义。

编辑:

根据你发布的Objective-C代码,我将猜测你的代码转换为Swift:

 //Make sure the call to NSURL(string:) works. If not, bail out. guard let imageURL= NSURL(string: "coffeemugDirectLink") else { print("unable to convert 'coffeemugDirectLink' to a URL") return } //Make sure the call to UIImage(named:) works. If not, bail out. guard let placeholderImage = UIImage(named: "heart.png") else { print("unable to load image with name 'heart.png'") return } cell.imageView.setImageWithURL(imageURL, placeholderImage: placeholderImage) 

顺便说一句,“coffeemugDirectLink”看起来不像一个有效的string转换为NSURL