Paste gif image into NSPasteboard - macos

I am developing osx application. I want to paste an Gif image into pasteboard. How can I do that?
What I have is
NSImage
NSPasteboard
What I want to do is to paste that image into pasteboard. I am able to paste PNG image but what I need is to paste GIF image.
My existing code
let imageURL = imageObject.imageURL!
let fileName = imageURL.lastPathComponent
var saveURL = NSURL(string: "file://" + NSTemporaryDirectory())
saveURL = saveURL?.URLByAppendingPathComponent(fileName!)
// I have data now
let data = NSData(contentsOfURL: imageURL)
pasteboard.declareTypes([NSTIFFPboardType], owner: nil)
pasteboard.setData(data!, forType: "com.compuserve.gif")

About 10 years ago same one asked How do I put a GIF onto an NSPasteboard?
in an Apple discussion group and here is my answer. Although 10 years old and the NSPasteboard methods changed since that time my answer still works. I confess: my advice is a bit dirty.

Okay I got it working after spending 6 hours searching online.
Basically I have to download the image file and paste it as a filename.
let imageURL = imageObject.imageURL!
let fileName = imageURL.lastPathComponent
var saveURL = NSURL(string: "file://" + NSTemporaryDirectory())
saveURL = saveURL?.URLByAppendingPathComponent(fileName!)
let data = NSData(contentsOfURL: imageURL)
data?.writeToURL(saveURL!, atomically: true)
pasteboard.declareTypes([NSFilenamesPboardType], owner: nil)
pasteboard.writeObjects([saveURL!])

I managed to get this working using the following code:
let pb = NSPasteboard.general
do {
let fileType = try NSWorkspace.shared.type(ofFile: localPath.path)
let pasteboardType = NSPasteboard.PasteboardType.init(fileType)
pb.declareTypes([pasteboardType], owner: nil)
pb.writeObjects([localPath as NSURL])
} catch {
return
}

Related

Load an image from a Base64-encoded string [duplicate]

This question already has answers here:
Decode Base-64 encoded PNG in an NSString
(6 answers)
Closed 5 years ago.
So I have an empty image view inside a .xib file. And there is another .m file that is a string but there an image loaded inside of it. Can someone please explain in detail how to load the image from the string and put it inside the imageview thats in the xib file?
If it's base64 string, you could use this type of website to extract it : http://codebeautify.org/base64-to-image-converter
In swift you could use this code to get the Image:
let dataFromBase64 = NSData(base64EncodedString: yourString, options: NSDataBase64DecodingOptions(rawValue: 0))!
let image = UIImage(data: dataFromBase64)!
yourImageView.image = image
Hope it helps.
Pierre
For Swift 3.
extension String {
public func base64ToImage() -> UIImage? {
if let dataDecoded = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters) {
return UIImage(data: dataDecoded)
}
return nil
}
}
Them you call:
if let image = yourBase64Image.base64ToImage() {
imageView.image = image
}
Hope it helps.

Swift 3 base64 encode image for upload

I have some nice code that allows me to pic and image and then display it in app. I was also uploading the profilePic.image to my database (as a blob) but I realised that this was not actually uploading the image itself but just data about the image so I could not render anything back as there was nothing to decode. So I want to transform this function to get the chosen image and encode it to base64 and utilise same working upload
func imagePickerController(
_ selectImage: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : AnyObject])
{
let chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage //2
// imageByCroppingToRect()
profilePic.contentMode = .scaleAspectFit //3
profilePic.image = chosenImage //4
dismiss(animated: true, completion: nil) //5
}
You have to convert the UIImage to a format your website can read, e.g. jpeg before encoding it in base 64.
let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = UIImageJPEGRepresentation(chosenImage, jpegCompressionQuality)?.base64EncodedString() {
// Upload base64String to your database
}
Note: In iOS 12 UIImageJPEGRepresentation was replaced by an instance method jpegData of UIImage:
let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = chosenImage.jpegData(compressionQuality: jpegCompressionQuality)?.base64EncodedString() {
// Upload base64String to your database
}
Refer to the Apple documentation for UIImageJPEGRepresentation and Data
Data has a function to return a base64 representation of itself as another Data. No need to convert to String and back.
Take a look at the docs for Data.base64EncodedData()
if let data = UIImageJPEGRepresentation(photos, 0.5)?.base64EncodedData() {
form.append(data, withName: "images", fileName: "photo.jpeg", mimeType: "image/jpeg")
}

AVPlayer doesn't play video from my parse

I'm trying to play video from my parse server
I'm getting empty video player
And when i print the url i get the correct video url
let thevideo:PFFile! = (self.selectedmsg["file"] as! PFFile)
let url:NSURL = NSURL(string: thevideo.url!)!
let player = AVPlayer(URL: url)
let playercontroller = AVPlayerViewController()
playercontroller.player = player
self.presentViewController(playercontroller, animated: true) {
player.play()
}
Any help?
I had the same issue, tried to search around for solution, but cannot, the only workable solution is save the file to device, and play it locally.

Simple Swift file download with URL

So I have the URL as string (in this case a JPG but would like a general procedure for any file type if possible) and I have the file path as string where I want to save the file.
What would be the fastest way to get this implemented?
Please keep in mind this is for OSX command line application. I tried few sample codes found here, mostly using UIImage but I get error:"Use of unresolved identifier", adding "import UIKit" gets me error:"No such Module". Please help!
import Foundation
let myURLstring = "http://www.safety.vanderbilt.edu/images/staff/Bob-Wheaton.jpg"
let myFilePathString = "/Volumes/HD/Staff Pictures/Bob-VEHS.jpg"
---> ABOVE IS THE ORIGINAL QUESTION <---
---> BELOW IS NEW IMPROVED CODE: WORKING <---
import Foundation
let myURLstring = "http://www.safety.vanderbilt.edu/images/staff/Bob-Wheaton.jpg"
let myFilePathString = "/Volumes/HD/Staff Pictures/Bob-VEHS.jpg"
let url = NSURL(string: myURLstring)
let imageDataFromURL = NSData(contentsOfURL: url)
let fileManager = NSFileManager.defaultManager()
fileManager.createFileAtPath(myFilePathString, contents: imageDataFromURL, attributes: nil)
If you're writing for OS X, you'll use NSImage instead of UIImage. You'll need import Cocoa for that - UIKit is for iOS, Cocoa is for the Mac.
NSData has an initializer that takes a NSURL, and another that takes a file path, so you can load the data either way.
if let url = NSURL(string: myURLstring) {
let imageDataFromURL = NSData(contentsOfURL: url)
}
let imageDataFromFile = NSData(contentsOfFile: myFilePathString)
With Swift 4, the code will be:
if let url = URL(string: myURLstring) {
let imageDataFromURL = try Data(contentsOf: url)
}

List files in iTunes shared folder using Swift

I would like to list all files in my iTunes shared folder in a 'Table View' using Swift.
I check on Google and nobody talk about it, it look like it's a uncommon need, so if anyone can help it would be really helpful.
EDIT: I found three links talking about it but in Objective-C, I have no experience in this language. If someone understand this, here are the links.
http://www.exampledb.com/objective-c-get-itunes-file-sharing-folder-files-with-full-path.htm
http://www.infragistics.com/community/blogs/stevez/archive/2013/10/14/ios-objective-c-working-with-files.aspx
http://www.raywenderlich.com/1948/itunes-tutorial-for-ios-how-to-integrate-itunes-file-sharing-with-your-ios-app
Based on this objective-C tutorial http://mobiforge.com/design-development/importing-exporting-documents-ios, I created three methods: listFilesFromDocumentsFolder which returns a list of the names of all documents I have in the apps iTunes shared folder and loadFileFromDocumentsFolder which loads the url for a given filename and passes the url to handleDocumentOpenUrl to load the file on a UIWebView. Find below the three methods.
You can also download the project from github: https://github.com/Euniceadu/Load-Shared-Documents
listFilesFromDocumentsFolder
func listFilesFromDocumentsFolder() {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var documentsDirectory : String;
documentsDirectory = paths[0] as String
var fileManager: NSFileManager = NSFileManager()
var fileList: NSArray = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: nil)!
var filesStr: NSMutableString = NSMutableString(string: "Files in Documents folder \n")
for s in fileList {
filesStr.appendFormat("%#", s as String)
}
self.displayAlert(filesStr)
}
loadFileFromDocumentsFolder
func loadFileFromDocumentsFolder(fileName: String) {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var documentsDirectory : String;
documentsDirectory = paths[0] as String
var filePath: String = documentsDirectory.stringByAppendingPathComponent(fileName);
var fileUrl: NSURL = NSURL(fileURLWithPath: filePath);
self.handleDocumentOpenURL(fileUrl)
}
handleDocumentOpenUrl
func handleDocumentOpenURL(url: NSURL) {
var requestObj = NSURLRequest(URL: url)
webView.userInteractionEnabled = true
webView.loadRequest(requestObj)
}
Hope this helps.

Resources