----- 存入 APP 的目录 Documents 中 ------
let urlStr = NSURL(string: "http://images.macx.cn/forum/201301/18/061737r4zfhs4bsrkrnrsq.jpg")
let data = NSData(contentsOf: urlStr! as URL)
//如果没有图片
if(data == nil){
print("no img")
return;
}
let image = UIImage(data: data! as Data)
//要写入的文件夹路径和图片名
let dt:String = NSHomeDirectory().appending("/Documents/").appending("2.png") as String;
/*打印路径: 可通过 finder 然后 快捷键 ctrl+shift+g 前往文件夹功能 进入 如下文件夹
/Users/admin/Library/Developer/CoreSimulator/Devices/8C4DA6F7-4431-402A-92A9-E83087F5159D/data/Containers/Data/Application/4935114D-926D-4EDA-918D-FA14EE023A34/Documents/2.png
*/
//将Image文件写入 如上的文件夹
try? UIImagePNGRepresentation(image!)?.write(to: URL(fileURLWithPath: dt))
//读取 文件夹 中 的 图片
let img2 = UIImage(contentsOfFile: dt)
//如果没有找到本地图片
if(img2 == nil){
print("not find local img")
return;
}
let imageView = UIImageView(image: img2)
imageView.contentMode = .center
imageView.frame = CGRect(x: 0, y: 0, width: 400, height: 200);
imageView.backgroundColor = UIColor.blue
self.view.addSubview(imageView)
本地的HTML 读取 以上存入的图片
//获取Documents在本机的路径
let docu:String = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0];
//向HTML注入JS 改变图片的src
wkwebview.evaluateJavaScript("document.getElementById('ffee').setAttribute('src','file://"+docu+"/3g.163.com_big.png');");
---------存入相册 -------
在 info.plist 中添加权限
Privacy - Photo Library Usage Description
let image = UIImage(data: data! as Data)
UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
--------- 存入剪贴板 --------
let image = UIImage(data: data! as Data)
UIPasteboard.general.image = image