IOS使用SDWebImage从URL加载图像

时间:2016-08-25 21:27:40

标签: ios json swift uiimage sdwebimage

我正在尝试使用以下内容从json网址加载图片,但我在[cell.imageView setImageWithURL:[NSURL URLWithString:@"coffeemugDirectLink"] placeholderImage:[UIImage imageNamed:@"heart.png"]];上收到错误错误为Expected ',' separatorExpected expression in container literal我做错了什么?如何在UICollectionView中将json中的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.
    }

}

2 个答案:

答案 0 :(得分:1)

那一行:

 [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"看起来不像是一个有效的字符串,无法转换为NSURL

答案 1 :(得分:1)

您的代码存在一些问题。您要问的问题是将一些Objective-C语法转储到Swift程序的中间,但更大的问题是您没有将从cellForItemAtIndexPath可以在API中检索到的数据存储起来得到它。

此外,cellForItemAtIndexPath需要是视图控制器类上的实例方法,可以根据需要由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
    }
}

有些纯粹主义者可能会抱怨我的力量展开占位符图像,但老实说如果失败了,你的应用程序资产就会出现问题,而且崩溃会在开发时告诉你。

相关问题