iOS Dropbox get thumbnails images - ios

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 !

Related

Firebase Storage Upload Error in Share Extensions

I'm creating an app with App Extension and I'm having trouble uploading files to firebase storage.
I choose a photo that I chose from the Photos application or another application for my own application by pressing the share button.
I am getting the URL of the selected photo in ShareViewController.
if let items = (self.extensionContext?.inputItems.first as? NSExtensionItem)?.attachments {
let contentType = kUTTypeData as String
for item in items {
item.loadItem(forTypeIdentifier: contentType, options: nil) { url, error in
if let path = url as? NSURL {
URLs.append(path.absoluteString!)
}
else {}
}
}
}
I'm trying to upload the URLs I get this way to firebase storage.
let uploadTask = riversRef.putFile(from: URLs[0], metadata: nil) { metadata, error in
guard let metadata = metadata else {
return
}
...
}
There is a problem with the URL of the selected photo but I can't quite understand it. I can get the size, name and other properties of the photo from the URL. I can even copy this photo to another directory with FileManager. I'm getting the URL from FileManager but still getting the same error. But when I try to install I get the following error.
Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown error occurred, please check the server response." UserInfo={bucket=appBucketName, _NSURLErrorFailingURLSessionTaskErrorKey=BackgroundUploadTask <9381D3C6-241C-4737-9589-BA5A7CFAF9E4>.<1>, object=PATH/6B36F026-CD6E-4E00-8A19-C530DC606674.jpg, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"BackgroundUploadTask <9381D3C6-241C-4737-9589-BA5A7CFAF9E4>.<1>"
), NSLocalizedDescription=An unknown error occurred, please check the server response., ResponseErrorDomain=NSURLErrorDomain, ResponseErrorCode=-995}
Solutions I tried;
I will not use putData.
I tried App Groups. I already have the URL of the file. I need to install directly but it doesn't work.
extension FileManager {
func documentsDirectory() -> URL {
let path = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.name")
return path!
}
func uploadPath(srcURL: URL, name: String, completion: #escaping ((_ filePath: URL?) -> Void)) {
do {
let path = documentsDirectory().appendingPathComponent("tempory")
try FileManager.default.createDirectory(atPath: path.relativePath, withIntermediateDirectories: true, attributes: nil)
let fullPath = path.appendingPathComponent(name)
try FileManager.default.copyItem(at: srcURL, to: fullPath)
completion(fullPath)
}
catch {
completion(nil)
}
}
}
Note: I am using Firebase emulator and Xcode simulator. I don't have any problems with the main application.
If there is missing information or incorrect information, please warn, I will correct it. Thank you for your help in advance.

Download fails when on first use or app goes in background

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!
//
})

Failed to save UIImage in Photo Library in swift

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?

Create a directory and store files inside it in Swift

i am creating a directory so that i can save temp videos onto it as TempVideos is a folder now my video clips will be inside the folder...
func createTempDirectoryToStoreVideos(){
var error: NSError?
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
tempVideoPath = documentsDirectory.stringByAppendingPathComponent("TempVideos")
if (!NSFileManager.defaultManager().fileExistsAtPath(tempVideoPath!)) {
NSFileManager.defaultManager() .createDirectoryAtPath(tempVideoPath!, withIntermediateDirectories: false, attributes: nil, error: &error)
}
}
Now in these directory i want to store the videos as
func saveCompressVideoToTempDirectory(var compressedVideoUrl:NSURL?){
let data = NSData(contentsOfURL: compressedVideoUrl!)
var error:NSError?
var success = data?.writeToFile(tempVideoPath!, options: NSDataWritingOptions.AtomicWrite, error: &error)
println(error)
if let temp = success{
if temp {
println("success")
}else{
println("not valid ")
}
}
}
Howver i get error as
Optional(Error Domain=NSCocoaErrorDomain Code=512 "The operation
couldn’t be completed. (Cocoa error 512.)" UserInfo=0x17407f6c0
{NSFilePath=/var/mobile/Containers/Data/Application/F1140A9F-8D16-444B-8679-9ED1AD3F5E6A/Documents/TempVideos,
NSUnderlyingError=0x17424a320 "The operation couldn’t be completed. Is
a directory"})
Could you try createFileAtPath for that?
func createFileAtPath(_ path: String,
contents data: NSData?,
attributes attr: [String : AnyObject]?) -> Bool
The same thing concerns writeToFile:
func writeToFile(_ path: String,
options writeOptionsMask: NSDataWritingOptions) throws
where, look out, path is
The location to which to write the receiver's bytes. If path contains
a tilde (~) character, you must expand it with
stringByExpandingTildeInPath before invoking this method.
You should write this:
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var dirpath: String = paths[0] as String
let filepath = dirpath.stringByAppendingPathComponent("myOwnData.mov")

iOS Photo Library read access

After the user gave us permission to access his Camera Roll. We would like to grab the data and upload it to our services from inside our app.
Is there a way to access the video data from the file? The only way to open the video file is to create an AVAsset. But that's not enough for me.
I'm aware off
func requestExportSessionForVideo(_ asset: PHAsset!,
options options: PHVideoRequestOptions!,
exportPreset exportPreset: String!,
resultHandler resultHandler: ((AVAssetExportSession!,
[NSObject : AnyObject]!) -> Void)!) -> PHImageRequestID
But in my case I just want to upload the video to our service I don't want to do:
first copy the video by doing an export into my local app data
and then send that data up to our service.
delete the data.
This approach above uses a lot of extra space and time and users with full 16GB iPhones it doesn't work well.
Ok this is what I tried so far using the URL
var anAcces = sourceURL?.startAccessingSecurityScopedResource
if !NSFileManager.defaultManager().fileExistsAtPath(sourceURL!.path!) {
NSLog("not exist")
}
var aFileCoordinator = NSFileCoordinator(filePresenter:nil)
var anError: NSError?
aFileCoordinator.coordinateReadingItemAtURL(sourceURL!, options:.ForUploading, error:&anError, byAccessor: { (newURL: NSURL!) -> Void in
var data = NSData(contentsOfURL: newURL)
})
if let unError = anError {
NSLog("Error \(unError)")
}
sourceURL?.stopAccessingSecurityScopedResource
This logs the following:
2015-02-08 16:20:01.947 Cameo[15706:2288691] not exist
2015-02-08 16:20:01.991 Cameo[15706:2288691] Error Error Domain=NSCocoaErrorDomain Code=257 "The operation couldn’t be completed. (Cocoa error 257.)" UserInfo=0x170876480 {NSURL=file:///var/mobile/Media/DCIM/100APPLE/IMG_0155.MOV, NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0155.MOV, NSUnderlyingError=0x17005a9a0 "The operation couldn’t be completed. Operation not permitted"}
Thanks to Paul suggestion I figured it out:
You have to create an PHImageManager requestAVAssetForVideo session in that block you have access to the file and read its data from the url.
let imageManager = PHImageManager.defaultManager()
let videoRequestOptions = PHVideoRequestOptions()
videoRequestOptions.deliveryMode = .HighQualityFormat
videoRequestOptions.version = .Current
videoRequestOptions.networkAccessAllowed = true
videoRequestOptions.progressHandler = { (progress: Double, error: NSError!, stop: UnsafeMutablePointer<ObjCBool>, [NSObject : AnyObject]!) -> Void in
NSLog("Progress: %#", progress.description)
}
videoRequestOptions.progressHandler = { (progress: Double, error: NSError!, stop: UnsafeMutablePointer<ObjCBool>, [NSObject : AnyObject]!) -> Void in
NSLog("Progress: %#", progress.description)
}
imageManager.requestAVAssetForVideo(nextAsset, options: videoRequestOptions, resultHandler: { (avAsset: AVAsset!, avAudioMix: AVAudioMix!, info: [NSObject : AnyObject]!) -> Void in
if let nextURLAsset = avAsset as? AVURLAsset {
let sourceURL = nextURLAsset.URL
if NSFileManager.defaultManager().fileExistsAtPath(sourceURL.path!) {
NSLog("exist file")
}
var data = NSData(contentsOfURL: sourceURL)
if let aData = data {
NSLog("length : <\(aData.length)")
}
else {
NSLog("no data read.")
}
}
}
Regarding the issue:
Failed to issue sandbox extension for file file:///var/mobile/Media/DCIM/100APPLE/IMG_0730.MOV, errno = 1
My workaround for this issue was to create a temporary path which I was able to access the the Media-File:
Future<void> loadAssets() async {
List<Asset> resultList = <Asset>[];
String error = 'No Error Detected';
final temp = await Directory.systemTemp.create();
List<File> imagesFileList = [];
try {
resultList = await MultiImagePicker.pickImages(
maxImages: 300,
enableCamera: true,
selectedAssets: imagesAssetsList,
cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
materialOptions: MaterialOptions(
actionBarColor: "#abcdef",
actionBarTitle: "Example App",
allViewTitle: "All Photos",
useDetailsView: false,
selectCircleStrokeColor: "#000000",
),
);
} on Exception catch (e) {
error = e.toString();
}
if (!mounted) return;
for (int i = 0; i < resultList.length; i++) {
final data = await resultList[i].getByteData();
imagesFileList.add(await File('${temp.path}/img$i').writeAsBytes(
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes)));
print('pathnew: ${imagesFileList[i].path}');
await uploadFileToStorage(imagesFileList[i].path);
}
setState(() {
imagesAssetsList = resultList;
_error = error;
});
}
I hope it will work!

Resources