swift xcode 6.3.1中如何导入和使用SDWebImage

How to import and use SDWebImage in swift xcode 6.3.1

我是 Swift 的新手,现在正在制作一个项目,其中包括显示来自网络的许多照片,我知道我需要使用 SDWebImage。 我在这里和其他地方看到了相关问题,但都是 Objective-C 语法,对我不起作用。

到目前为止我做了什么:

  1. 我从 GitHub
  2. 下载了 zip
  3. 已将 SDWebImage 文件夹复制到我的文件夹
  4. 尝试了 import
  5. 的所有可能组合

#import <"SDWebImage/UIImageView+WebCache.h">

import SDWebImage/UIImageView+WebCache.h

等..

有人可以帮我导入吗

首先,您需要配置Bridging Header,描述为here at SO。使用以下内容:

#import <SDWebImage/UIImageView+WebCache.h>

这会将 Objective-C 代码导入 Swift 代码

其次,随便用,比如:

self.imageView.sd_setImageWithURL(self.imageURL)

据我了解,您已经有了一个桥接头,只需要组织您的导入。由于您没有使用 cocoapods 或 Carthage 将源文件直接复制到您的项目中,因此您可以这样导入:

#import "UIImageView+WebCache.h"

它对我有用的唯一方法(使用 mac os 10.11.4 和 ios 9.3)是这样的:

  1. 从 link 下载并解压框架:https://github.com/rs/SDWebImage/releases/download/3.6/SDWebImage-3.6.framework.zip:

  2. 将该框架拖到 x-code 项目中并选中选项:如果需要,复制项目(在项目导航器中,您现在应该看到手提箱图标,其中包含一个包含 .h 文件的文件夹)

  3. 创建新的桥接头文件:cmd+n -> 文件 -> 新建 -> 文件...和 ​​select "header" 模板图标
  4. 打开该文件,写入行(就在#endif: 上方)#import < SDWebImage/UIImageView+WebCache.h >(这是来自框架的头文件之一的路径)

  5. 上面@Azat 回答的第 most 重要步骤是在构建设置中将您刚刚创建的文件与项目连接:

    • select 项目名称(项目导航器中的蓝色图标)
    • select "Build Settings" 在你的右边开始输入 "Bridging header..." 并且当你有包含 "Objective-C Bridging header"
    • 的行时
    • 在该行的空白字段中按两次(window 弹出窗口),然后将桥接头文件从项目导航器拖到 window 中。

      1. 希望现在您可以使用库方法:imageView.setImageWithUrl(url, placeholderImage:)

Swift3.0代码

import SDWebImage

let url = URL.init(string: "https://vignette3.wikia.nocookie.net/zelda/images/b/b1/Link_%28SSB_3DS_%26_Wii_U%29.png")

  imagelogo.sd_setImage(with: url , placeholderImage: nil)

在swift 5.1中只需导入SdWebimage并使用扩展

扩展 UIImageView{

func downloadImage(url : String, placeHolder : UIImage?) throws{
    if let url = URL(string: url){
        self.sd_imageIndicator?.startAnimatingIndicator()
        self.sd_setImage(with: url) { (image, err, type, url) in

            if err != nil{
                    self.sd_imageIndicator?.stopAnimatingIndicator()
                    print("Failed to download image")
                }
                self.sd_imageIndicator?.stopAnimatingIndicator()
            }
        }

    }
}