iOS8 Photo Extension says Unable to save changes - swift

I am trying to create an iOS Photo Extension which compresses images, and this is finishContentEditingWithCompletionHandler function:
func finishContentEditingWithCompletionHandler(completionHandler: ((PHContentEditingOutput!) -> Void)!) {
dispatch_async(dispatch_get_global_queue(CLong(DISPATCH_QUEUE_PRIORITY_DEFAULT), 0)) {
atomically: true)
let url = self.input?.fullSizeImageURL
if let imageUrl = url {
var fullImage = UIImage(contentsOfFile:
imageUrl.path!)
//Just compresses the image
let renderedJPEGData =
UIImageJPEGRepresentation(fullImage, self.comprestionRatioFloat)
var currentFilter = "FakeFilter"
renderedJPEGData.writeToURL(
output.renderedContentURL,
atomically: true)
let archivedData =
NSKeyedArchiver.archivedDataWithRootObject(
currentFilter)
output.adjustmentData = PHAdjustmentData(formatIdentifier:"MyApp.Ext", formatVersion:"1.0", data:archivedData)
}
completionHandler?(output)
// Clean up temporary files, etc.
}
}
When I test it on the device it says "Unable to Save Changes", Is there anything wrong?

Finally I've found out it's because the output image is almost the same as input. A little scaling down the output image fixed the problem.

Related

Unable to save images in the right directory

I am trying to save images in a directory. Images are correctly saved in the right place, but when I inspect these with the path in the finder, all the images are damaged and unsable.
damaged images
Below the static method:
static func writeImageFile(with data: Data, issue: Issue, page: Int, isThumbnail: Bool) throws -> URL {
let url = MediaFileManager.issueImagesDirectoryURL(issue: issue).ensuringDirectoryExists()
let imageURL = url.appendingPathComponent(imageName(for: page, isThumbnail: isThumbnail))
try data.write(to: imageURL)
return url
}
And the call in the class:
DispatchQueue.main.async {
guard let data = result.data else {
self.downloadDidFail(for: result.page)
return
}
do {
let writeImageFile = try MediaFileManager.writeImageFile(with: data, issue: self.issue, page: result.page, isThumbnail: false)
let writeThumbFile = try MediaFileManager.writeImageFile(with: data, issue: self.issue, page: result.page, isThumbnail: true)
print(writeImageFile)
print(writeThumbFile)
} catch let error as NSError {
print(error.localizedDescription)
}
}
I will assume, since you don't quite specify this, that you have a bunch of UIImage objects.
And I also noticed that you want your images to be saved as JPEG, which is no trouble at all, don't worry.
I would go with something like this:
if let image = UIImage(named: "example.png") {
if let data = UIImageJPEGRepresentation(image, 1.0) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}
}
Where the func getDocumentsDirectory() is the following:
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
You might wonder why I used 1.0 for the second parameter in UIImageJPEGRepresentation, well that's the JPEG quality mapped between 0.0 and 1.0 (it's a float).
If you have any details that I am not aware of, please reply and I will try to help accordingly.
Hope it helps you, cheers!
Source: link
Have you tried to load the image to a UIImageView to see if the images are being properly downloaded? imageView.image = UIImage(data: data).
But I also detect that you're saving Data instead of the image, in order to make sure that you're saving an image I would try the following
static func writeImageFile(with data: Data, issue: Issue, page: Int, isThumbnail: Bool) throws -> URL {
let url = MediaFileManager.issueImagesDirectoryURL(issue: issue).ensuringDirectoryExists()
let imageURL = url.appendingPathComponent(imageName(for: page, isThumbnail: isThumbnail))
let image = UIImage(data: data)
let imgData = UIImageJPEGRepresentation(image, 1)
try imgData.write(to: imageURL)
return url
}
Yes, it might have unnecessary steps, worth trying, this way we're making sure that it's saved as Jpeg. But again, I would check if the images are being properly downloaded first.

Save UIImage array to disk

I have a UIImage array that I'm trying to save to disk (documents directory). I've converted it to Data so it can be saved but I can't figure out the correct/best way to save that [Data] to disk.
(arrayData as NSArray).write(to: filename, atomically: false) doesn't seem right or there seems like there is some better way.
Code so far:
// Get the new UIImage
let image4 = chartView.snapShot()
// Make UIImage into Data to save
let data = UIImagePNGRepresentation(image4!)
// Add Data image to Data Array
arrayData.append(data!)
// Get Disk/Folder
let filename = getDocumentsDirectory().appendingPathComponent("images")
// This is how I'd Write Data image to Disk
// try? data?.write(to: filename)
// TODO: Write array Data images to Disk
(arrayData as NSArray).write(to: filename, atomically: false)
To save your images to the document directory, you could start by creating a function to save your image as follows. The function handles creating the image name for you and returns it.
func saveImage(image: UIImage) -> String {
let imageData = NSData(data: UIImagePNGRepresentation(image)!)
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let docs = paths[0] as NSString
let uuid = NSUUID().uuidString + ".png"
let fullPath = docs.appendingPathComponent(uuid)
_ = imageData.write(toFile: fullPath, atomically: true)
return uuid
}
Now since you want to save an array of images, you can simply loop and call the saveImage function:
for image in images {
saveImage(image: image)
}
If you prefer to name those images yourself, you can amend the first function to the following:
func saveImage(image: UIImage, withName name: String) {
let imageData = NSData(data: UIImagePNGRepresentation(image)!)
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let docs = paths[0] as NSString
let name = name
let fullPath = docs.appendingPathComponent(name)
_ = imageData.write(toFile: fullPath, atomically: true)
}
When you save an image as a UIImagePNGRepresentation as you are trying to do, please note that is does not save orientation for you. This means that when you attempt to retrieve the image, it might be titled to the left. You will need to redraw your image to make sure it has the right orientation as this post will explain how to save png correctly. However, if you save your image with UIImageJPEGRepresentation you will not have to worry about all that and you can simply save your image without any extra effort.
EDITED TO GIVE ARRAY OF IMAGES
To retrieve the images you have saved, you can use the following function where you pass an array of the image names and you get an array back:
func getImage(imageNames: [String]) -> [UIImage] {
var savedImages: [UIImage] = [UIImage]()
for imageName in imageNames {
if let imagePath = getFilePath(fileName: imageName) {
savedImage.append(UIImage(contentsOfFile: imagePath))
}
}
return savedImages
}
Which relies on this function to work:
func getFilePath(fileName: String) -> String? {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
var filePath: String?
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if paths.count > 0 {
let dirPath = paths[0] as NSString
filePath = dirPath.appendingPathComponent(fileName)
}
else {
filePath = nil
}
return filePath
}
You can below code to stored image into local.
let fileManager = NSFileManager.defaultManager()
let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("ImageName.png")
let image = YOUR_IMAGE_TO_STORE.
let imageData = UIImageJPEGRepresentation(image!, 0.5)
fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)

WKWebView CALayer to image exports blank image

I'm trying to take a screenshot of webpage but the image is always blank(white).
I'm using this code to convert CALayer to Data(taken from here)
extension CALayer {
/// Get `Data` representation of the layer.
///
/// - Parameters:
/// - fileType: The format of file. Defaults to PNG.
/// - properties: A dictionary that contains key-value pairs specifying image properties.
///
/// - Returns: `Data` for image.
func data(using fileType: NSBitmapImageFileType = .PNG, properties: [String : Any] = [:]) -> Data {
let width = Int(bounds.width * self.contentsScale)
let height = Int(bounds.height * self.contentsScale)
let imageRepresentation = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)!
imageRepresentation.size = bounds.size
let context = NSGraphicsContext(bitmapImageRep: imageRepresentation)!
render(in: context.cgContext)
return imageRepresentation.representation(using: fileType, properties: properties)!
}
}
And then to write the data to file as .png
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
{
let d = web.layer?.data() as NSData? //web is the instance of WKWebView
d!.write(toFile: "/Users/mac/Desktop/web.png", atomically: true)
}
But I'm getting a blank(white) png instead of what I expected
1). What am I doing wrong?
2). Is there any other possible ways to get the image representation of
webpage(Using swift)?
Thank you!
Latest Update:
Now you can take screenshot of WKWebView just like WebView.
Apple added new method for both iOS and macOS,
func takeSnapshot(with snapshotConfiguration: WKSnapshotConfiguration?,
completionHandler: #escaping (NSImage?, Error?) -> Void)
But its still in beta.
You can't take a screenshot of WKWebView. It always returns a blank image. Even if you try to include WKWebView inside another NSView and take a screenshot, it will give you blank image in place of WKWebView.
You should use WebView instead of WKWebView for your purpose. Check this question.
If you are ok with using private frameworks(apple doesn't allow your app in its store), check this GitHub. Its written in Obj-C. I don't know Obj-C so I can't explain what's happening in that code. But it claims to do the work.
Your best approach is to use WebView and use your mentioned extension data() on the WebView.
Just a question: Why don't you use phantomJS?
PS. Sorry for the late reply. I didn't see your e-mail.
Update: Swift 5 adding to prior.
I didn't want controls in the output, so I bound a key sequence to it (local key monitor):
case [NSEvent.ModifierFlags.option, NSEvent.ModifierFlags.command]:
guard let window = NSApp.keyWindow, let wvc = window.contentViewController as? WebViewController else {
NSSound(named: "Sosumi")?.play()
return true
}
wvc.snapshot(self)
return true
and work within a sandbox environment. We keep a bunch of user settings in the defaults like where they want snapshots to be captured (~/Desktop), so 1st time around we ask/authenticate, cache it, and the app delegate on subsequent invocations will restore sandbox bookmark(s).
var webImageView = NSImageView.init()
var player: AVAudioPlayer?
#IBAction func snapshot(_ sender: Any) {
webView.takeSnapshot(with: nil) {image, error in
if let image = image {
self.webImageView.image = image
} else {
print("Failed taking snapshot: \(error?.localizedDescription ?? "--")")
self.webImageView.image = nil
}
}
guard let image = webImageView.image else { return }
guard let tiffData = image.tiffRepresentation else { NSSound(named: "Sosumi")?.play(); return }
// 1st around authenticate and cache sandbox data if needed
if appDelegate.isSandboxed(), appDelegate.desktopData == nil {
let openPanel = NSOpenPanel()
openPanel.message = "Authorize access to Desktop"
openPanel.prompt = "Authorize"
openPanel.canChooseFiles = false
openPanel.canChooseDirectories = true
openPanel.canCreateDirectories = false
openPanel.directoryURL = appDelegate.getDesktopDirectory()
openPanel.begin() { (result) -> Void in
if (result == NSApplication.ModalResponse.OK) {
let desktop = openPanel.url!
_ = self.appDelegate.storeBookmark(url: desktop, options: self.appDelegate.rwOptions)
self.appDelegate.desktopData = self.appDelegate.bookmarks[desktop]
UserSettings.SnapshotsURL.value = desktop.absoluteString
}
}
}
// Form a filename: ~/"<app's name> View Shot <timestamp>"
let dateFMT = DateFormatter()
dateFMT.dateFormat = "yyyy-dd-MM"
let timeFMT = DateFormatter()
timeFMT.dateFormat = "h.mm.ss a"
let now = Date()
let path = URL.init(fileURLWithPath: UserSettings.SnapshotsURL.value).appendingPathComponent(
String(format: "%# View Shot %# at %#.png", appDelegate.appName, dateFMT.string(from: now), timeFMT.string(from: now)))
let bitmapImageRep = NSBitmapImageRep(data: tiffData)
// With sandbox clearance to the desktop...
do
{
try bitmapImageRep?.representation(using: .png, properties: [:])?.write(to: path)
// https://developer.apple.com/library/archive/qa/qa1913/_index.html
if let asset = NSDataAsset(name:"Grab") {
do {
// Use NSDataAsset's data property to access the audio file stored in Sound.
player = try AVAudioPlayer(data:asset.data, fileTypeHint:"caf")
// Play the above sound file.
player?.play()
} catch {
Swift.print("no sound for you")
}
}
} catch let error {
NSApp.presentError(error)
NSSound(named: "Sosumi")?.play()
}
}

Issue setting UIImageView from local image in documents directory

I am trying to load images that I have downloaded using Alamofire to the documents directory. I store the filenames in a Realm database. Once it is time to display the image I take the path to the documents directory and append the filename. This path doesn't seem to work for building a UIImage though.
if let name = playlist.RLMsongs[indexPath.row].name, let imageURL = playlist.RLMsongs[indexPath.row].album?.image?.getImageURL(.SmallImage), let fileName = playlist.RLMsongs[indexPath.row].album?.image?.smallLocalFileName {
cell.songName.text = name
let range = imageURL.rangeOfString("http")
if let theRange = range where theRange.startIndex == imageURL.startIndex { // imageURL starts with "http" (remote url)
cell.albumImage.sd_setImageWithURL(NSURL(string: imageURL), placeholderImage: UIColor.imageFromColor(UIColor.grayColor())) {
_ in
cell.albumImage.fadeIn(completion: nil)
}
} else {
cell.albumImage.image = UIImage(named: fileName) // images still do not load
// tried this first -> cell.albumImage.sd_setImageWithURL(NSURL(fileURLWithPath: imageURL), placeholderImage: UIColor.imageFromColor(UIColor.grayColor()))
}
}
Here is the bit that builds the path (imageURL above):
let documentsDir = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let path = documentsDir.URLByAppendingPathComponent(localFile).path
return path
As per TiM's recommendation I checked the value of imageURL on a breakpoint and it looks just fine:
imageURL: "/Users/danielnall/Library/Developer/CoreSimulator/Devices/0B8D64B5-9593-4F86-BBD3-E408682C5C0F/data/Containers/Data/Application/011E4805-40EB-4221-9D7D-1C1D64660186/Documents/75.9226ecd6893cb01a306c974d9d8ffd62803109c1.png"
This is the full path on the simulator and is only missing the file schema (file://) which for the use of NSURL fileURLWithPath should be just fine I think.
If you already have the PNG file in Documents then all you need to do is this.
(Assuming that cell.albumImage is UIImageView)
let imageFileName = "75.9226ecd6893cb01a306c974d9d8ffd62803109c1.png"
cell.albumImage.image = UIImage(named: imageFileName)
Check if file exists:
func fileExists(filePath: String) -> Bool {
let filemanager = NSFileManager.defaultManager()
if filemanager.fileExistsAtPath(filePath) {
return true
}
return false
}
I ended up finding the solution to the problem which was unrelated to the direction of this question. Turned out that the issue was in my override of the prepareForReuse method in my UITableViewCell class. Thank you for everyone's suggestions though.

amazon S3 Swift - simple upload take ages and finally doesnt show up in bucket

I m trying to send a photo on an S3 bucket. Well, this is hell of undocumented in swift, and sdks are fragmented here and there, it s a big mess on my side and nothing works so far :
My uploading process goes on, but extremely slow (let s say a 5 meg image takes 10 minutes) and most of the time, the upload freezes and starts over again.
But the weird thing is when It finally succeeds, the file doesn t show up in my bucket. I ve tried uploading files to non existing buckets and the process still goes on (???)
here are my credentials loc (bucket is in east california)
let credentialsProvider = AWSCognitoCredentialsProvider(
regionType: AWSRegionType.USEast1, identityPoolId: "us-east-1:47e88493-xxxx-xxxx-xxxx-xxxxxxxxx")
let defaultServiceConfiguration = AWSServiceConfiguration(
region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = defaultServiceConfiguration
now here s my upload function
func uploadImage(){
//defining bucket and upload file name
let S3BucketName: String = "witnesstestbucket"
let S3UploadKeyName: String = "public/testImage.jpg"
let expression = AWSS3TransferUtilityUploadExpression()
expression.uploadProgress = {(task: AWSS3TransferUtilityTask, bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) in
dispatch_async(dispatch_get_main_queue(), {
let progress = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
print("Progress is: \(progress)")
print (Float(totalBytesExpectedToSend))
})
}
self.uploadCompletionHandler = { (task, error) -> Void in
dispatch_async(dispatch_get_main_queue(), {
if ((error) != nil){
print("Failed with error")
print("Error: \(error!)");
}
else{
print("Sucess")
}
})
}
let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()
transferUtility.uploadData(imagedata, bucket: S3BucketName, key: S3UploadKeyName, contentType: "image/jpeg", expression: expression, completionHander: uploadCompletionHandler).continueWithBlock { (task) -> AnyObject! in
if let error = task.error {
print("Error: \(error.localizedDescription)")
}
if let exception = task.exception {
print("Exception: \(exception.description)")
}
if let _ = task.result {
print("Upload Starting!")
}
return nil;
}
}
#IBAction func post(sender: UIButton) {
// AW S3 upload
uploadImage()
}
to make it clear, My imagedata NSData comes from a uiimage, fetched from a collectionviewcell:
self.imagedata = UIImageJPEGRepresentation(img!, 05.0)!
Is there anything I could update to understand where I am wrong ?
thanks in advance :)
ok, was trying to upload NSData file using the uploaddata request, here is the working code with proper URL swift2 conversion :
func uploadImage(){
let img:UIImage = fullimage!.image!
// create a local image that we can use to upload to s3
let path:NSString = NSTemporaryDirectory().stringByAppendingString("image2.jpg")
let imageD:NSData = UIImageJPEGRepresentation(img, 0.2)!
imageD.writeToFile(path as String, atomically: true)
// once the image is saved we can use the path to create a local fileurl
let url:NSURL = NSURL(fileURLWithPath: path as String)
// next we set up the S3 upload request manager
uploadRequest = AWSS3TransferManagerUploadRequest()
// set the bucket
uploadRequest?.bucket = "witnesstest"
// I want this image to be public to anyone to view it so I'm setting it to Public Read
uploadRequest?.ACL = AWSS3ObjectCannedACL.PublicRead
// set the image's name that will be used on the s3 server. I am also creating a folder to place the image in
uploadRequest?.key = "foldername/image2.jpeg"
// set the content type
uploadRequest?.contentType = "image/jpeg"
// and finally set the body to the local file path
uploadRequest?.body = url;
// we will track progress through an AWSNetworkingUploadProgressBlock
uploadRequest?.uploadProgress = {[unowned self](bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64) in
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self.amountUploaded = totalBytesSent
self.filesize = totalBytesExpectedToSend;
print(self.filesize)
print(self.amountUploaded)
})
}
// now the upload request is set up we can creat the transfermanger, the credentials are already set up in the app delegate
let transferManager:AWSS3TransferManager = AWSS3TransferManager.defaultS3TransferManager()
// start the upload
transferManager.upload(uploadRequest).continueWithBlock { (task) -> AnyObject? in
// once the uploadmanager finishes check if there were any errors
if(task.error != nil){
print("%#", task.error);
}else{ // if there aren't any then the image is uploaded!
// this is the url of the image we just uploaded
print("https://s3.amazonaws.com/witnesstest/foldername/image2.jpeg");
}
return "all done";
}
}
I would like to thank Barrett Breshears for the Help, and his GithubSource is from 2014 but I could manage to convert it easily because of this clear and well commented piece of code