问题引出
最近公司做一个项目,为了安全要求所有的图片资源采用Ftp协议的方式访问。iOS项目图片缓存自然选择了SDWebImage, 可是它如何加载Ftp协议的图片呢?是不是一时间蒙住了?其实很简单。
解决办法
只需要将用户名与密码封装到图片url里即可。
NSString path = @"ftp://username:password@192.168.1.1/img/1.png";
[self.imgView sd_setImageWithURL:[NSURL URLWithString:path]];
示例项目
开启mac下 ftp服务器
sudo -s launchctl load -w /System/Library/LaunchDaemons/ftp.plist
sudo -s launchctl unload -w /System/Library/LaunchDaemons/ftp.plist
在用户路径下建立一个img文件夹 放了三张图片
建立一个示例iOS工程
cocopod 安装SDWebImage 当前最新版本是 3.8. 地址是 https://github.com/rs/SDWebImage
pod init 后 打开 podfile 添加一行
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'FtpImageDemo' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for FtpImageDemo
pod 'SDWebImage', '~>3.8'
target 'FtpImageDemoTests' do
inherit! :search_paths
# Pods for testing
end
target 'FtpImageDemoUITests' do
inherit! :search_paths
# Pods for testing
end
end
SDWebImge安装成功
storyboard的控制器中 放入三个ImageView 连好线,写如下代码
#import "ViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imgView1;
@property (weak, nonatomic) IBOutlet UIImageView *imgView2;
@property (weak, nonatomic) IBOutlet UIImageView *imgView3;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self configViews];
}
- (void)configViews
{
NSString *path1 = @"ftp://ruglcc:123456@192.168.1.100/img/1.jpg";
NSString *path2 = @"ftp://ruglcc:123456@192.168.1.100/img/2.jpg";
NSString *path3 = @"ftp://ruglcc:123456@192.168.1.100/img/3.jpg";
[self.imgView1 sd_setImageWithURL:[NSURL URLWithString:path1]];
[self.imgView2 sd_setImageWithURL:[NSURL URLWithString:path2]];
[self.imgView3 sd_setImageWithURL:[NSURL URLWithString:path3]];
}
编译运行,有图有真相