Im new to dropbox Core API. Previously i have some experience with making calls to instagram api's with NSURLSession on the treehouse course I'm on. However I'm stuck here. Iv called the method
- (void)restClient:(DBRestClient *)client loadedMetadata:(DBMetadata *)metadata {
if (metadata.isDirectory) {
NSLog(#"Folder '%#' contains:", metadata.path);
for (DBMetadata *file in metadata.contents) {
[self.pathsArray addObject:file.path];
NSLog(#"----%#", pathsArray);
}
}
//reloads view to see images
[self.collectionView reloadData];
}
Which has given me an array of the file path location. I then wrote
NSString *paths = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[self.filePaths lastPathComponent]]];
`for (NSString *file in self.filePaths) {
[self.restClient loadFile:file intoPath:paths];
}`
which downloads the images correctly however, because the loaded file method returns null i am unsure how create an array of the downloaded images to display in my UICollectionViews cell?
The loadFile method in the Dropbox for iOS Core SDK says:
/* Loads the file contents at the given root/path and stores the result into destinationPath */
- (void)loadFile:(NSString *)path intoPath:(NSString *)destinationPath;
This means the downloaded content (for the file on Dropbox at path) is saved to the local filesystem at the local path destinationPath.
You can use this delegate method to know when this is done:
- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)destPath;
To get the content for the downloaded file once you've been notified it is done, you need to read the downloaded file from the local file system. For example, you might load it using NSString stringWithContentsOfFile:encoding:error, or whatever the relevant next step is for you.
Related
In my application I need to capture image as well as save it on local library and on server using FTP. Now I need to follow a format for image name while saving it on the server. I am able to capture and save the image on local library. But I am unable to find any method to change the name of the Image. Suppose I need to rename it as Productname-UserId.png Is there any way? Kindly help.
Thank you.
UIImagePNGRepresentation(UIImage*) is likely what you're looking for. You can save a UIImage as a PNG file in the Application Documents folder, then upload that to a server. The code to do this is quite trivial, so if you could post the code you're trying to use, that would be helpful to understanding, and recommending a solution for you.
Here's a short clipping from my code that does exactly this:
UIImage * image; // Some image you want to send
NSString * docDirWithSlash = [[self applicationDocumentsDirectory] stringByAppendingString:#"/"];
NSString * pngFile = [docDirWithSlash stringByAppendingString:file]; // <-- Change the string "file" to reflect the name you want.
[UIImagePNGRepresentation(image) writeToFile:pngFile atomically:YES];
// Send pngFile to the server here
Where applicationDocumentsDirectory looks like this:
- (NSString *) applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
return documentsDirectoryPath;
}
The real question here is where do you want the file name to be specific? On the device or on the server. In case of device use Charles answer, otherwise you should look at http protocol(file upload part). Actually it doesn't matter what name the file have on you local device, as when you send it to the server over http, you can provide any name. The tricky part here is that the server you are uploading to should take that parameter into account when saving that file. So if you are uploading to a server that you don't have hand on and it does some self naming convention - you probably stuck. If it's yours - look at how you're saving files on the server side and if you are taking in account that "filename" parameter...P.S. And don't forget to pass that argument to the upload request :)
I am wanting to write my own logs to a text file on my iPhone. I wrote up a quick method that writes a string to a file. Right now it saves it into the Documents directory, which, if on the device is going to be a pain to get off, since I can't just browse to it. Is there a better way to quickly get this file off the device after I have written to it?
/**
* Logs a string to file
*
* #version $Revision: 0.1
*/
+ (void)logWithString:(NSString *)string {
// Create the file
NSError *error;
// Directory
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"log.txt"];
// Get the file contents
NSData *localData = [NSData dataWithContentsOfFile:filePath];
if (localData) {
NSString *logString = [[NSString alloc] initWithData:localData encoding:NSUTF8StringEncoding];
string = [logString stringByAppendingFormat:#"%#\n", string];
[logString release];
}
// Write to the file
[string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
}//end
Add Application supports iTunes file sharing to your application target's build info in Xcode:
Then, you can easily browse, retrieve and delete any files created by the app from iTunes, right under Devices > Your device > Apps > File Sharing:
You may have to capture what number of logs you have created so far and create a new name for each log biased on that.
So you might save your last made logs name as a string in NSUserDefaults and get the number off the end of that and add one onto that captured int ready for the next name.
So if you have #"Log4" you can get the 4 out of that and make it 5 so that the next log is named "Log5"
Just my 2 cents :P
With regard to the 'How to get the file' part of the question
iExplorer, previously iPhone Explorer allows you to view your apps, including their documents folder without jailbreaking your devices.
In my experience (albeit of an older version), getting the files from the phone can be a little temporamental (i.e. I drag a file onto my desktop and although it creates the file, it doesn't write any of the data), you can get the files from your device.
Our iPad app can show Documents and save them offline when needed.
I've got a QLPreviewController subclass named DocumentViewController (named DVC from now on) for showing them.
Workflow of the app:
- The user clicks a name of a document and the DVC is pushed on to show the document.
- The DVC downloads the file offline and shows it when done.
(So the HTTP URL is downloaded, stored offline, and an offline URL is returned)
The weird thing is, is that only PDF files are working with the offline URL, and the rest crashes.. (it works with online links though)
I did some tests and when I put file:// before the offline link the app does not crash but the DVC is ging me some information about the file (like that it is a excel 97-2004 document).
So some info is transferred, but I can't figure out what the problem is.
Here are some screenshots and after that some code.
code:
Note that Document is a model class with document properties like id, name, file type and url.
//DVC QLPreviewController dataSource method for returning url
- (id <QLPreviewItem>) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger)index
{
[SaveHelper saveDocumentFileAndPropertyWithDocument:document];
//[SaveHelper getDocumentFileWithDocument:document]; without file://
//if I return document.documentUrl it is working with all files except iworks files)
return [SaveHelper getDocumentFileAsPathWithDocument:document]; //with file://
}
//SaveHelper methods
+ (NSString *)documentFilePathWithDocument:(Document *)document
{
return [[self documentFilePath] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#%d.%#", DOCUMENT_FILE_PREFIX, document.documentId, document.documentType]];
}
+ (NSURL *)saveDocumentFileAndPropertyWithDocument:(Document *)document
{
if([self saveDocumentPropertyWithDocument:document])
{
return [self saveDocumentFileWithDocument:document];
}
return nil;
}
+ (NSURL *)saveDocumentFileWithDocument:(Document *)document
{
NSData *data = [NSData dataWithContentsOfURL:document.documentURL];
NSString *fullPath = [self documentFilePathWithDocument:document];
if([[NSKeyedArchiver archivedDataWithRootObject:data] writeToFile:fullPath atomically:YES])
{
return [NSURL fileURLWithPath:fullPath];
}
return nil;
}
+ (NSURL *)getDocumentFileWithDocument:(Document *)document
{
return [NSURL fileURLWithPath:[self documentFilePathWithDocument:document]];
}
+ (NSURL *)getDocumentFileAsPathWithDocument:(Document *)document
{
return [NSURL fileURLWithPath:[#"file://" stringByAppendingPathComponent:[[self getDocumentFileWithDocument:document] absoluteString]]];
}
If more code needed, just say.
EDIT:
When logging the URL passed trough the 'getDocumentFileAsPathWithDocument' method:
url: file:/var/mobile/Applications/xx-xx/Documents/documentFiles/file_20.pdf
url: file:/var/mobile/Applications/xx-xx/Documents/documentFiles/file_80.docx
Where the PDF file is working and the docx not
When I try to load an image(jpg) from local storage I get a black screen with this error message:
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.5 (8L1)/Symbols/System/Library/Frameworks/QuickLook.framework/DisplayBundles/Image.qldisplay/Image (file not found).
warning: No copy of Image.qldisplay/Image found locally, reading from memory on remote device. This may slow down the debug session.
EDIT:
The webview does not work either with the local urls. PDF is fine but the office files gives an message "Unable to read Document, the file format is invalid". The iWorks documents give the same error as the quicklook. I think its somewhere at the save and load of the format, I savve them as a NSDATA but after that there is no hint for the iPad to see if it is for example a word document (only the extension).
You haven't posted your download code, but I believe that the problem is there. Files from Pages (.pages extension) aren't actual files, they are bundles, i.e. directories that contain files and show as a single item in Finder (look up a .pages file in Finder, right-click it and select 'Show contents'). Downloading a .pages file is actually like downloading a directory: it depends on the web server what kind of result you get but it's most likely an error page.
You could detect that it's a .pages file and try to download all of its contents manually, but you'd have to study the structure of the files to see if that's possible because it's unlikely that you can request the contents of the directory from a web server.
The results for the .ppt and .xls files look normal to me; I think it unlikely that the iPad can preview MS Office documents at all.
Edit: apologies, I just read that iOS can preview MS Office documents. Perhaps the documents get somehow corrupted during download? Have you tried to set your download location to the app's documents folder and enable iTunes file sharing? That way you can download some documents, pull them off your device and then try to open it on your PC to see if that works.
We finally found the solution!
I was right that the problem was with saving the document.
I needed to change the save method in:
+ (NSURL *)saveDocumentFileWithDocument:(Document *)document
{
NSData *data = [NSData dataWithContentsOfURL:document.documentURL options:NSDataReadingUncached error:nil];
NSString *fullPath = [self documentFilePathWithDocument:document];
if([[NSFileManager defaultManager] createFileAtPath:fullPath contents:data attributes:nil])
{
return [NSURL fileURLWithPath:fullPath];
}
//OLD CODE
// if([[NSKeyedArchiver archivedDataWithRootObject:data] writeToFile:fullPath atomically:YES])
// {
// return [NSURL fileURLWithPath:fullPath];
// }
return nil;
}
SO saving it with the filemanager and not with a keyedarchiver.
Did you check if the size of the files is the same both online and offline? It is possible that the file download wasn't complete
Try using the URL of the MS Office documents with a normal NSURL object and opening in a UIWebView. Does it work then (so we know if its the document or your class)?
Try using NSURL's fileURLWithPath: method in the getDocumentFileAsPathWithDocument: It is possible that the URL being returned is incorrect (though doesn't look like it from the logs but doesn't hurt to try)
first of all, use this code to make sure your documents are there,because i think the error cause by your documents path.
NSFileManager *fileManager=[NSFileManager defaultManager];
if([fileManager fileExistsAtPath:fullPath]){
NSLog(#"%# exsit! ",fullPath);
}else{
NSLog(#"%# not exsit! ",fullPath);
}
If any of one have same problem even though you did everything suggestions above.
(I had same problem, when I downloaded some files from google drive.)
Try this!
Put 'x' end of your file extension to be recognized as a new version of format.
(it's working only for 'doc' and 'ppt' files, not for 'xls' files)
Yes, I know this is not a appropriate way to solve this problem, but
it's worth to try it.
Believe me I tried everything!
Hope you help.
A very basic question concerning dropBox integration into an iPhone app.
I followed the setup of the DropBoxSDK and everything works fine. I can log on to my account and get it linked. So I set up everything correctly.
Now I would like to use it to simply load a file from the dropBox and save it again. Consider that you only want to sync ONE FILE (for the sake of simplicity), called 'example.txt' which is located in the 'Example' folder in my DropBox. The same 'example.txt' is saved locally on the iPhone in the Documents directory of my app.
The dropBox readme file suggest vaguely the following code which I find highly cryptic and can't really see how to load or save a file:
2. Make an request on the rest client:
[[self restClient] loadMetadata:#"/"];
3. Implement the DBRestClientDelegate methods needed to get the results of the
particular call you made:
- (void)restClient:(DBRestClient*)client
loadedMetadata:(DBMetadata*)metadata {
NSLog(#"Loaded metadata!");
}
- (void)restClient:(DBRestClient*)client
metadataUnchangedAtPath:(NSString*)path {
NSLog(#"Metadata unchanged!");
}
- (void)restClient:(DBRestClient*)client
loadMetadataFailedWithError:(NSError*)error {
NSLog(#"Error loading metadata: %#", error);
}
So my (hopefully) simple question is how I can:
check if there is an example folder in my dropbox
if not, create one and save the example.txt from app documents into this example folder
load example.txt
once programme quits: save example.txt to DropBox
I can't really find an answer to these quite basic steps in the DropBox docs on the website. The example they've provided I find too confusing... especially as it is only about loading files and not saving them as far as I can see.
I'd be grateful for any help or suggestions of how to go about this.
Ok, I found this method to save my example.txt file:
-(void) DBupload:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Example.txt"];
[self.restClient uploadFile:#"NoteBook.txt" toPath:#"/example" fromPath:filePath];
}
Turns out, no need to create a folder, dropbox will do this automatically for you if it doesn't exist.
This is for downloading the same file form dropbox:
-(void) DBdownload:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Example.txt"];
NSError *error;
[self.restClient loadFile:#"/example/Example.txt" intoPath:filePath];
if (filePath) { // check if file exists - if so load it:
NSString *tempTextOut = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&error];
}
}
Hope this helps if you were struggling with a similar question.
Into the DBdownload function you can skip the check by implementing the DBRestClientDelegate method loadedFile and loadFileFailedWithError
I have a property list file which gets to the bundle when I build my program. Now, I would like to be to modify it with my Mac and get it updated while my program is running. I guess bundling the file is not the correct approach, as I do not seem to have any access to the contents of the bundle after it has been built.
How should I approach? It would be nice to work at least with the iPhone simulator but it would be veeery nice to work with the device too.
Your application bundle is signed, so it can not be modified after it is created/signed.
In order to modify the plist, you need to copy it to the Documents directory for your application first. You can then modify the copy. Here is a method that I have in one of my apps that copies a file called FavoriteUsers.plist from the bundle to the documents directory during app start up.
/* Copies the FavoritesUsers.plist file to the Documents directory
* if the file hasn't already been copied there
*/
+ (void)moveFavoritesToDocumentsDir
{
/* get the path to save the favorites */
NSString *favoritesPath = [self favoritesPath];
/* check to see if there is already a file saved at the favoritesPath
* if not, copy the default FavoriteUsers.plist to the favoritesPath
*/
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:favoritesPath])
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"FavoriteUsers" ofType:#"plist"];
NSArray *favoriteUsersArray = [NSArray arrayWithContentsOfFile:path];
[favoriteUsersArray writeToFile:favoritesPath atomically:YES];
}
}
/* Returns the string representation of the path to
* the FavoriteUsers.plist file
*/
+ (NSString *)favoritesPath
{
/* get the path for the Documents directory */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
/* append the path component for the FavoriteUsers.plist */
NSString *favoritesPath = [documentsPath stringByAppendingPathComponent:#"FavoriteUsers.plist"];
return favoritesPath;
}
Sort of. You have read-only access to the bundle, so what you need to do is copy over the plist from your bundle into your app's documents folder.
The documents folder is an area of your application's sandbox where you can read and write to files. So if you copy the plist there upon the very first launch of your app, you'll be able to edit and modify it to your heart's content.
There's a tutorial somebody wrote online that basically answers your exact question, so rather than try to do my own explanation here's a much better one!
http://iphonebyradix.blogspot.com/2011/03/read-and-write-data-from-plist-file.html