I am using swift PHPhotoLibrary class to save image in photo library. Below is my code:
PHPhotoLibrary.sharedPhotoLibrary().performChanges( {
let assetCreation = PHAssetCreationRequest.creationRequestForAssetFromImage(self.photoView.image!)
let imageData = UIImageJPEGRepresentation((self.photoView?.image)!,1)
let option = PHAssetResourceCreationOptions()
assetCreation.addResourceWithType(PHAssetResourceType.FullSizePhoto, data: imageData!, options: option)
},
completionHandler: {
success, error in
if success {
print("save image success" )
} else {
print(error)
}
})
But I always got this error message: Optional(Error Domain=NSCocoaErrorDomain Code=-1 "(null)")
This error was printed by the else line: "print(error)"
Does anyone know what the problem is?
Related
While trying to save a photo to a custom album on some devices we get the following error:
The operation couldn’t be completed. (PHPhotosErrorDomain error 3300).
code: 3300
This is the part of the code where the issue happens
PHPhotoLibrary.shared().performChanges({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
guard let placeholder = assetChangeRequest.placeholderForCreatedAsset else { return }
let albumChangeRequest = PHAssetCollectionChangeRequest(for: album)
albumChangeRequest?.addAssets([placeholder] as NSArray)
}, completionHandler: { success, error in
completion(success, error)
})
I would be thankful for any tips since I am out of ideas.
#available(iOS 8, *)
open func addAssets(_ assets: NSFastEnumeration)
have a try albumChangeRequest.addAssets([placeholder] as NSFastEnumeration)
here is the Apple Document
I am trying to use the PHPickerViewController to select images from my photo gallery and seeing the following error.
Could not create a bookmark: NSError: Cocoa 257 "The file couldn’t be
opened because you don’t have permission to view it
I am using Xcode 12.5 on Mac M1 (macOS 11.2.3) And connecting to an iPhone 12 (IOS 14.8).
The code in question appears to throw the above exception in the call to loadFileRepresentation. I have also tried loadInPlaceFileRepresentation and loadObject with similar results.
private func getPhoto(from itemProvider: NSItemProvider) {
print(itemProvider.registeredTypeIdentifiers)
itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier) { url, error in
if let error = error {
print("Encountered Error in loadFileRepresentation \(error.localizedDescription)")
}
if url != nil {
print("Obtained url: \(String(describing: url))")
} else {
print("Could not obtain url")
}
let imageData = try! Data(contentsOf: url!)
DispatchQueue.main.async {
self.parent.mediaItems.append(item: PhotoPickerItem(with: UIImage(data:imageData)!))
}
}
}
I can see that the itemProvider has the following representations.
["public.heic", "public.jpeg"]
and I have tried UTType.jpeg.identifier as well.
Any pointers would be greatly appreciated
Alamofire 3.5.0, Swift2.2
I'm downloading ZIP files with the Alamofire download method, I've noticed that when I'm starting download process and apps goes background than the download fails with following error:
----------------------
error Optional(Error Domain=NSCocoaErrorDomain Code=4
"“CFNetworkDownload_pZ56nc.tmp” couldn’t be moved to “courses”
because either the former doesn't exist, or the folder containing
the latter doesn't exist." UserInfo=
{NSSourceFilePathErrorKey=
/private/var/mobile/Containers/Data/Application/[UUID]/tmp/CFNetworkDownload_pZ56nc.tmp,
NSUserStringVariant=(
Move
),
NSDestinationFilePath=
/var/mobile/Containers/Data/Application/[UUID]/Library/courses/course_302.zip,
NSFilePath=
/private/var/mobile/Containers/Data/Application/[UUID]/tmp/CFNetworkDownload_pZ56nc.tmp,
NSUnderlyingError=0x13f52f990 {Error Domain=NSPOSIXErrorDomain
Code=2 "No such file or directory"}})
----------------------
this is the code to download a file:
//...
var userLibraryPath:String = {
return NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0]
}()
//...
let _coursePath:NSURL = NSURL(string: "file://\(userLibraryPath)/)")!
//...
let zipURL = _coursePath.URLByAppendingPathComponent("course_\(courseId).zip")
//if file exists destroy it
if let zipPath = zipURL?.path where NSFileManager.defaultManager().fileExistsAtPath(zipPath) {
do {
try NSFileManager.defaultManager().removeItemAtPath(zipPath)
} catch let error as NSError {
print(error)
}
}
//
let downloadRequest = Alamofire.download(Router.download(courseId), destination: { (url:NSURL, urlResponse:NSHTTPURLResponse) -> NSURL in
//
return zipURL!
//
}).progress({ (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
//
let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
dispatch_async(GlobalMainQueue, {
self.notifyDownloadProgress(courseId, progress: progress)
})
}).response(completionHandler: { (request:NSURLRequest?, response:NSHTTPURLResponse?, data:NSData?, error:NSError?) in
self.removeFromQueue(courseId)
print("response")
print("----------------------")
print("error \(error)")
print("----------------------")
//here I would try to extract it
})
UPDATE I've just tested on iPhone 5 fresh install of the app and it doesn't have to go to background (e.g. via home button) to fail, it fails on the very first load (and any subsequent) untill after the app is killed and reopened.
Why is the "/private" bit added to the path? What am I doing wrong here?
And indeed it was a "No such file or directory" error.
When I've added:
//
let downloadRequest = Alamofire.download(Router.download(courseId), destination: { (url:NSURL, urlResponse:NSHTTPURLResponse) -> NSURL in
let course = zipURL!.URLByDeletingLastPathComponent!.path!
let fm = NSFileManager.defaultManager()
var isDir:ObjCBool = false
if(fm.fileExistsAtPath(path, isDirectory: &isDir) == false){
//doesnt exist
do {
try fm.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
//
print(error)
}
}
return zipURL!
//
})
So i'm using AVFoundation to make a camera, but for some reason i keep getting this error when i go to capture, most of the time it results in my phone losing connection to Xcode and crashing the app, I also use it to crop images and get the same sort of error.
Is anybody able to tell me why this error occurs?
Communications error: <OS_xpc_error: <error: 0x19b14ca80> { count = 1,
contents = "XPCErrorDescription" => <string: 0x19b14ce78> {
length = 22, contents = "Connection interrupted" } }>
Here is the code for the capture:
public func capturePictureWithCompletition(imageCompletition: (UIImage?, NSError?) -> Void) {
var blockHandler = { (imageDataSampleBuffer: CMSampleBuffer?, error: NSError?) -> Void in
if let imageDataSampleBuffer = imageDataSampleBuffer {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
let image = UIImage(data: imageData)
imageCompletition(image?.normalizedImages, nil)
} else {
imageCompletition(nil, error)
}
}
if self.cameraIsSetup {
if self.cameraOutputMode == .StillImage {
if let stillImageOutput = self.stillImageOutput {
let connection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo)
stillImageOutput.captureStillImageAsynchronouslyFromConnection(connection, completionHandler: blockHandler)
}
}
}
}
It seems to be a memory crashing problem.
Try to resize your image.
This question can help you: How to Resize image in Swift?
I'm trying to load thumbnails images of a Dropbox account, but I got a bug. I create a local directory in the first method to put thumbnails, and I make a request to load them, but it doesn't works.
Here is my code :
// Create directory method
func createTempDirectory() -> String? {
let tempDirectoryTemplate = NSTemporaryDirectory()
tempDirectoryTemplate.stringByAppendingPathComponent("XXXXX")
let fileManager = NSFileManager.defaultManager()
var err: NSErrorPointer = nil
if fileManager.createDirectoryAtPath(tempDirectoryTemplate, withIntermediateDirectories: true, attributes: nil, error: err) {
return tempDirectoryTemplate
}
else {
return nil
}
}
// Get thumbnails images
func restClient(client: DBRestClient!, loadedMetadata metadata: DBMetadata!) {
temporaryDirectory = createTempDirectory()!
for file in metadata.contents {
if (file.thumbnailExists == true) {
client.loadThumbnail(file.path, ofSize: "s", intoPath: temporaryDirectory)
}
}
self.collectionView?.reloadData()
}
And this is the error :
[WARNING] DropboxSDK: error making request to /1/thumbnails/dropbox/star.jpg - (4) Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)
Thanks for your help !