Reputation: 840
I have been able to get one image to save to a selected url but I need to save multiple NSImages with custom names. I would have preferred to save all the images into a directory then save the directory but I cant save anything to the directory after it is made. This is the code I have to save the single image from a NSSavepanel. (image1 is an NSImage(). It has been set to a file dragged and dropped into the app. Then it is resized).
func save() {
let dialog = NSSavePanel()
dialog.title = "Save file"
dialog.showsResizeIndicator = false
dialog.canCreateDirectories = true
dialog.showsHiddenFiles = true
dialog.allowedFileTypes = ["png"]
if (dialog.runModal() == NSApplication.ModalResponse.OK) {
let result = dialog.url
if (result != nil) {
let picture = image1
picture.writePNG(toURL: result!)
print("saved at \(result!)")
}
} else {
print("Cancel")
return // User clicked cancel
}
}
This is the code I have to write the image to the url:
public extension NSImage {
public func writePNG(toURL url: URL) {
guard let data = tiffRepresentation,
let rep = NSBitmapImageRep(data: data),
let imgData = rep.representation(using: .png, properties: [.compressionFactor : NSNumber(floatLiteral: 1.0)]) else {
print("\(self.self) Error Function '\(#function)' Line: \(#line) No tiff rep found for image writing to \(url)")
return
}
do {
try imgData.write(to: url)
}catch let error {
print("\(self.self) Error Function '\(#function)' Line: \(#line) \(error.localizedDescription)")
}
}
}
Upvotes: 1
Views: 993
Reputation: 53000
You need to use NSOpenPanel
to obtain a destination folder from your user. Set the options so that the user can only select folders and can create new folders. You will get returned a URL to the existing or newly created folder. You can now create as many files (and subfolders) as you wish within the folder.
Upvotes: 4