----- Stored in APP's directory Documents ------
let urlStr = NSURL(string: "http://images.macx.cn/forum/201301/18/061737r4zfhs4bsrkrnrsq.jpg") let data = NSData(contentsOf: urlStr! as URL) //if there is no image if(data == nil){ print("no img") return; } let image = UIImage(data: data! as Data) //The folder path and image name to be written let dt:String = NSHomeDirectory().appending("/Documents/").appending("2.png") as String; /*Print path: You can enter the following folder through the finder and then the shortcut key ctrl+shift+g to go to the folder function /Users/admin/Library/Developer/CoreSimulator/Devices/8C4DA6F7-4431-402A-92A9-E83087F5159D/data/Containers/Data/Application/4935114D-926D-4EDA-918D-FA14EE023A34/Documents/2.png */ //Write the Image file to the above folder try? UIImagePNGRepresentation(image!)?.write(to: URL(fileURLWithPath: dt)) // read the pictures in the folder let img2 = UIImage(contentsOfFile: dt) //If no local image is found 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)
The local HTML reads the image stored above
//Get the path of Documents in this machine let docu:String = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]; //Inject JS into HTML to change the src of the image wkwebview.evaluateJavaScript("document.getElementById('ffee').setAttribute('src','file://"+docu+"/3g.163.com_big.png');");
---------Save in photo album-------
Add permissions in info.plist
Privacy - Photo Library Usage Description
let image = UIImage(data: data! as Data) UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
--------- Save to clipboard ---------
let image = UIImage(data: data! as Data) UIPasteboard.general.image = image