IOS 使用 SDWebImage 从 URL 加载图像

IOS load images from URL using SDWebImage

我正在尝试使用以下内容从 json URL 加载图像,但在 [cell.imageView setImageWithURL:[NSURL URLWithString:@"coffeemugDirectLink"] placeholderImage:[UIImage imageNamed:@"heart.png"]]; 上出现错误,错误是 Expected ',' separatorExpected expression in container literal 我做错了什么?如何将 json 中的 URL 加载到我的 UICollectionView 单元格中?

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.
    }

}

那一行:

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

...是 Objective-C 代码在您的 Swift 程序中间。那是行不通的。您需要将该代码转换为 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”看起来不像是转换为 NSURL.

的有效字符串

您的代码有几个问题。你问的那个是由于将一些 Objective-C 语法转储到 Swift 程序的中间造成的,但你更大的问题是你没有存储从 API 你的 cellForItemAtIndexPath 可以得到它的任何地方。

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

您需要创建一个数组来存储您的杯子,并创建一个结构来放入数组。

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
    }
}

一些纯粹主义者可能会抱怨我强行展开占位符图像,但老实说,如果这样做失败了,那么您的应用程序资产就会出现问题,并且在开发时崩溃会告诉您这一点。