Knowing when a file has uploaded to Dropbox - iphone

I have managed to get my app to upload to Dropbox like so:
NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
[self.restClient uploadFile:#"ZipTest.zip" toPath:[NSString stringWithFormat:#"/%#", self.dropboxFolderName] fromPath:docsPath];
But am now trying to verify it actually completed the upload. I know I can check for errors but how to check for completion?
I have tried using:`- (void)restClient:(DBRestClient*)client uploadProgress:(CGFloat)progress forFile:(NSString *)destPath from:(NSString *)srcPath {
Buut all I get is the number 1 printed even though I see on Dropbox the file has not completed the upload yet?
any ideas?
Thanks`

- (void)restClient:(DBRestClient *)client uploadedFile:(NSString *)srcPath {
NSString *filename = [[srcPath pathComponents]lastObject];
NSString *message = [NSString stringWithFormat:#"Uploaded File:%#",filename];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success"
message:message delegate:nil cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
I used this code to check file is uploaded or not and after uploading this alert will show

Related

How to add timestamp to my filePath?

I have a static file path to a download folder, files download fine but when I download a new one the old one gets replaced by new. I suppose because of static pathing. How do I add a timestamp to my code so whenever a new download is made the old one wouldn't get replaced?Or maybe even give download file the "original" filename from the actual array?
here is my download code:
-(void) Savefile {
[self.downloadfile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Wooopss!" message:#"Download failed. Try Again..." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else if (data) {
[data writeToFile:#"/Users/Danny/Desktop/PDFFile/hello.pdf" atomically:NO ];
NSLog(#"Downloading file...");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Downloading" message:#"File is being downloaded..." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}];
}
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"MMddYYYYmmss"];
NSString *filePath = [NSString stringWithFormat:#"/Users/Danny/Desktop/PDFFile/hello_%#.pdf", [dateFormatter stringFromDate:[NSDate date]]];
Which will give you this:
/Users/Danny/Desktop/PDFFile/hello_032620144401.pdf
Not entirely sure what you mean by:
Or maybe even give download file the "original" filename from the
actual array

iphone: copy or move file from document directory folder

Here is my code.
NSArray *pathSong = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *toPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"Songs"];
NSString *fromPath=[[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"abc"];
NSString *strdestination = [fromPath stringByAppendingPathComponent:#"sg.mp3"];
NSError *Error;
if([[NSFileManager defaultManager]fileExistsAtPath:strdestination]){
if([[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error]==NO){
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"copy" message:[NSString stringWithFormat:#"%#",Error] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[Alert show];
}
else{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Not copy" message:[NSString stringWithFormat:#"%#",Error] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[Alert show];
}
}
I am getting the error logo :
Error Domain=NSCocoaErrorDominCode=516 "The operation couldn't be
completed .(Cocoa arrow 516.)" userInfo=0x681abf0
NSUnderlyingError =0x681b920 "The operation couldn't be completed
.File exists"
abc folder there is no song name "sg.mp3" but I'm still getting the file exists error. I don't know where I did mistake?
There is two issues in your code:
You need to remove the file if it is already there
You need to specify a name for the destination file, means if you use like:
NSString *toPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"Songs"];
and
[[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error];
Then if copy occurs, it will copy the Sg.mp3 file as Songs without any type.
So you need to write it like:
NSArray *pathSong = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *tempPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"Songs"];
NSString *toPath = [tempPath stringByAppendingPathComponent:#"yourFileName.mp3"];
NSString *fromPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"abc"];
NSString *strdestination = [fromPath stringByAppendingPathComponent:#"sg.mp3"];
NSError *Error = nil;
if([[NSFileManager defaultManager]fileExistsAtPath:strdestination])
{
if([[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error]==NO)
{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"copy" message:[NSString stringWithFormat:#"%#",Error] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[Alert show];
}
else
{
[fileManager removeItemAtPath:strdestination error:NULL];
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Not copy" message:[NSString stringWithFormat:#"%#",Error] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[Alert show];
}
}
This code will remove the file if exist at destination and then copy the sg.mp3 from abc folder to Songs folder with the name yourFileName.mp3
Drawing upon the Midhun MP answer, here's a helper
BOOL moveFile(NSString *srcPath, NSString *dstPath)
{
NSLog(#"moving %# -> %#", srcPath, dstPath);
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:dstPath])
{
// in my usecase this is a hard error, bolt to prevent overwriting
return NO;
}
if ([fm fileExistsAtPath:srcPath])
{
NSError *error = nil;
NSString *destDir = [dstPath stringByDeletingLastPathComponent];
[fm createDirectoryAtPath:destDir withIntermediateDirectories:YES attributes:nil error:nil];
if ([[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dstPath error:&error]==NO)
{
NSLog(#"failure declassing %#", srcPath);
return NO;
}
else
{
[fm removeItemAtPath:srcPath error:NULL]; // gr8t success
return YES;
}
}
return NO;
}
I think its because you are trying to overwrite a file with your copy.
Check your permission mask, try using the cache instead of the documents directory.
Do you mean if(!fileExistsAtPath)
You need to delete the file that's already there:
NSArray *pathSong = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *toPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"Songs"];
NSString *fromPath=[[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"abc"];
NSString *strdestination = [fromPath stringByAppendingPathComponent:#"sg.mp3"];
NSError *Error;
//DELETE THE FILE AT THE LOCATION YOU'RE COPYING TO
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:strdestination error:NULL];
if([[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error]==NO){
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"copy" message:[NSString stringWithFormat:#"%#",Error] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[Alert show];
}
else{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Not copy" message:[NSString stringWithFormat:#"%#",Error] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[Alert show];
}

Downloading files from uiwebview in iphone sdk

Is there any way to download file from UIWebView i am using this code on my IBAction event
- (IBAction)saveFile:(id)sender {
// Get the URL of the loaded ressource
NSURL *theRessourcesURL = [[self.webDisplay request] URL];
NSString *fileExtension = [theRessourcesURL pathExtension];
if ([fileExtension isEqualToString:#"png"] || [fileExtension isEqualToString:#"jpg"] ||
[fileExtension isEqualToString:#"pdf"] || [fileExtension isEqualToString:#"html"]) {
// Get the filename of the loaded ressource form the UIWebView's request URL
NSString *filename = [theRessourcesURL lastPathComponent];
NSLog(#"Filename: %#", filename);
// Get the path to the App's Documents directory
NSString *docPath = [self documentsDirectoryPath];
// Combine the filename and the path to the documents dir into the full path
NSString *pathToDownloadTo = [NSString stringWithFormat:#"%#/%#", docPath, filename];
// Load the file from the remote server
NSData *tmp = [NSData dataWithContentsOfURL:theRessourcesURL];
// Save the loaded data if loaded successfully
if (tmp != nil) {
NSError *error = nil;
// Write the contents of our tmp object into a file
[tmp writeToFile:pathToDownloadTo options:NSDataWritingAtomic error:&error];
if (error != nil) {
NSLog(#"Failed to save the file: %#", [error description]);
} else {
// Display an UIAlertView that shows the users we saved the file :)
UIAlertView *filenameAlert = [[UIAlertView alloc] initWithTitle:#"File saved" message:[NSString stringWithFormat:#"The file %# has been saved.", filename] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[filenameAlert show];
[filenameAlert release];
}
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning"
message:#"File could not be loaded"
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
[alert release];
// File could notbe loaded -> handle errors
}
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning"
message:#"File type not supported"
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
[alert release];
// File type not supported
}
}
this code open the file in UIWebView , which i want to download and when i press the button the opened file get save.
But i want my UIWebView to behave like normal browser , when the download link appear in it and user press it, UIWebView show dialog with option open it or save it if user press save the file get save automatically and if user press open it file should open in UIWebView.
You can provide webView:shouldStartLoadWithRequest in your UIWebViewDelegate so that each time the user is about to move to another web page, you have the chance to check what the link looks like:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[[request URL] scheme] isEqual:#"http"] &&
[[[request URL] pathExtension]...])
<your download/save code here>
return NO; //-- no need to follow the link
}
return YES; //-- otherwise, follow the link
}

Unable to show UIAlertView

in my app i am using validation keys to download content from a server using Wi-Fi. I need to show a UIAlert if the licence keys are wrong or if the wi-fi is not available. I have written the coed for displaying the alert view but the alert is not being displayed... This is scking the blood out my head... Can anyone help please....the control is going over this line, but still the alert is not being displayed.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory= [[[UIApplication sharedApplication] delegate] applicationDocumentsDirectory]; //[pathToStore objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingFormat:#"packages"];
NSString *packagePath = [NSString stringWithFormat:#"%#/%#", path,isbnTemp];
[recievedData writeToFile:[documentsDirectory stringByAppendingPathComponent:#"file.zip"] atomically:YES];
NSString *zipPath=[documentsDirectory stringByAppendingPathComponent:#"file.zip"];
[fileManager createDirectoryAtPath:documentsDirectory withIntermediateDirectories:NO attributes:nil error:nil];
ZipArchive *zipArchive = [[ZipArchive alloc]init];
if([zipArchive UnzipOpenFile:zipPath]){
if([zipArchive UnzipFileTo:packagePath overWrite:YES]){
[self loadContent];
}
else{
NSLog(#"Unable to UnArchieve the packages");
}
}
else {
NSLog(#"Failure To Open Archive");
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Your ISBN and/or Licence Key are incorrect" message:Nil delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
Are you trying to show the UIAlertView in a method that is being called from a thread other than the main thread? For example, if you are trying to show the UIAlertView in an asynchronous callback, it could be running on a separate thread.
If so, you need to move the code that shows the UIAlertView to a separate selector, and call it on the main thread using one of the performSelectorOnMainThread: methods.
For example, add the following method to your class:
-(void)showAlert {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Your ISBN and/or Licence Key are incorrect" message:Nil delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
And then change the last else clause in your current code so that it uses:
[self performSelectorOnMainThread:#selector(showAlert) withObject:nil waitUntilDone:NO];
See the NSObject class reference for more information on the performSelectorOnMainThread: methods.
After you've created the alert could you check for a NULL pointer in the alert variable?
Maybe you need to specify a message? Other than that I can't see anything wrong with the code you've posted.

iPhone: How to Write an Image to Disk in the App Directories

I am working on an iPhone project in which I need save camera images to disk and file but the code below fails:
(************
-(void)imagePickerController:(UIImagePickerController *) picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
imageView.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
imgglobal =imageView.image;
NSString *newFilePath = [NSHomeDirectory() stringByAppendingPathComponent: #"~/Users/abc/Library/Application Support/iPhone Simulator/User/Applications/SAVE_IMAGE_TEST1.JPG"];
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 1.0);
NSData *data = imageData;
if (imageData != nil) {
[imageData writeToFile:newFilePath atomically:YES];
}
if ([[NSFileManager defaultManager] createFileAtPath:#"~/Users/abc/Library/Application Support/iPhone Simulator/User/Applications/SAVE_IMAGE_TEST1.JPG" contents:data attributes:nil])
{
UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:#"Success" message:#"Image was successfully saved to the Photo Library." delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[successAlert show];
[successAlert release];
} else {
UIAlertView *failureAlert = [[UIAlertView alloc] initWithTitle:#"Failure" message:#"Failed to save image to the Photo Library." delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[failureAlert show];
[failureAlert release];
}
}
You shouldn't have a hard coded path to the simulator directories. That will fail on the device or when the simulator resets. Neither should you save user data anywhere but the app's Document folder.
Instead use:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathToDocuments=[paths objectAtIndex:0];
This will return the current path the app's Document directory regardless of where it is run or what has changed.
You should never use absolute paths in iPhone code because the system scrambles the paths for security. Always use the functions that dynamically retrieve the paths as needed.