繁体   English   中英

iOS使用SDWebImage从URL加载图像

[英]IOS load images from URL using SDWebImage

我正在尝试使用以下内容从JSON URL加载图像,但在[cell.imageView setImageWithURL:[NSURL URLWithString:@"coffeemugDirectLink"] placeholderImage:[UIImage imageNamed:@"heart.png"]]; 错误是Expected expression in container literal中的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"]];            

...是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的有效字符串。

您的代码有几个问题。 您要问的问题是由于将一些Objective-C语法转储到Swift程序的中间而引起的,但是更大的问题是您没有将从API检索到的数据存储在cellForItemAtIndexPath可以获取它的任何位置。

此外, 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
    }
}

一些纯粹主义者可能会抱怨我强行打开占位符图像,但是老实说,如果失败,您的应用程序资产就会混乱,崩溃会在开发时告诉您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM