Dropbox upload stops when you leave uiviewcontrolelr - ios

i am facing issue in dropbox upload.
When i am staying on the view on which i have written dropbox upload code then it works fine. But if in between upload process i leave the view and open another screen then upload stops or canceled.
I am using below code
- (void)didPressLink {
self.restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
self.restClient.delegate = self;
if(![[DBSession sharedSession] isLinked]) {
[[DBSession sharedSession] linkFromController:self];
}
}
-(void)saveFileOnDropBox{
[self didPressLink];
NSString *filename = [soundOneNew lastPathComponent];
NSString *destDir = #"/";
[[self restClient] uploadFile:filename toPath:destDir withParentRev:nil fromPath:soundOneNew];
}
-(void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath
from:(NSString*)srcPath metadata:(DBMetadata*)metadata {
NSLog(#"File uploaded successfully to path: %# %#", metadata.path, destPath);
[[self restClient] loadSharableLinkForFile: [NSString stringWithFormat:#"/%#",metadata.path]];
}
- (void)restClient:(DBRestClient*)client uploadFileFailedWithError:(NSError*)error {
NSLog(#"File upload failed with error - %#", error);
}
- (void)restClient:(DBRestClient*)restClient loadedSharableLink:(NSString*)link
forFile:(NSString*)path
{
NSLog(#"Sharable link %#",link);
NSLog(#"File Path %# ",path);
}
-(void) restClient:(DBRestClient *)client uploadProgress:(CGFloat)progress forFile:(NSString *)destPath from:(NSString *)srcPath {
static NSDate* date = nil;
static double oldUploadedFileSize = 0;
if (!date) {
date = [NSDate date] ;
} else {
NSTimeInterval sec = -[date timeIntervalSinceNow];
date = [NSDate date] ;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:srcPath error:nil];
double uploadedFileSize = (double)[fileAttributes fileSize] * progress;
if (sec) {
NSLog(#"speed approx. %.2f KB/s", (uploadedFileSize - oldUploadedFileSize )/1024.0 / sec );
}
oldUploadedFileSize = uploadedFileSize;
self.uploadAudioProgress.progress = progress;
}
}
How to keep upload process continue even if i leave the view

You call
self.restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
to create a new REST client and then
[[self restClient] uploadFile:filename toPath:destDir withParentRev:nil fromPath:soundOneNew];
to do the upload. So, this client is owned by the view controller and is destroyed when the view controller is destroyed - i.e. when you navigate away from it.
You want some other class and an instance of it (probably a singleton or an instance owned by the app delegate and passed to instances that need it) which owns all of the REST clients created and retains them until they are complete.

Related

cannot download file from google drive in ios

I am very new to IOS development, I am developing an app in which I want to download a file from Google Drive (pdf,doxc,doc and xlxs) and which will be sent to sent it to our server.
First I have installed it in pod file by using
pod 'GoogleAPIClient/Drive', '~> 1.0.2'
pod 'GTMOAuth2', '~> 1.1.0'
Second I created a project in Google Developer Console with bundle id and got client id, I have saved it into my project.
When user clicks select file button
-(IBAction)onclickfileFromDrive:(id)sender
{
self.service = [[GTLServiceDrive alloc] init];
self.service.authorizer = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName clientID:kClientID clientSecret:nil];
NSLog(#"service reply%hhd",self.service.authorizer.canAuthorize);
if (!self.service.authorizer.canAuthorize)
{
[self presentViewController:[self createAuthController] animated:YES completion:nil];
}
else
{
[self fetchFiles];
}
}
- (GTMOAuth2ViewControllerTouch *)createAuthController
{
GTMOAuth2ViewControllerTouch *authController;
NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeDrive, nil];
authController = [[GTMOAuth2ViewControllerTouch alloc]
initWithScope:[scopes componentsJoinedByString:#" "]
clientID:kClientID
clientSecret:nil
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
return authController;
}
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController finishedWithAuth:(GTMOAuth2Authentication *)authResult error:(NSError *)error
{
if (error != nil)
{
[self showAlert:#"Authentication Error" message:error.localizedDescription];
self.service.authorizer = nil;
}
else
{
self.service.authorizer = authResult;
[self dismissViewControllerAnimated:YES completion:nil];
}
self.service.authorizer = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName clientID:kClientID clientSecret:nil];
NSLog(#"service reply%hhd",self.service.authorizer.canAuthorize);
if (self.service.authorizer.canAuthorize)
{
[self fetchFiles];
}
}
The process of login is working fine here I am getting access token and refresh token
while I am trying to download a file
- (void)fetchFiles
{
GTLQueryDrive *query =[GTLQueryDrive queryForFilesList];
query.q = #"mimeType ='application/pdf' or mimeType ='text/plain' or mimeType ='application/msword' or mimeType ='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' or mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'";
[self.service executeQuery:query delegate:self didFinishSelector:#selector(displayResultWithTicket:finishedWithObject:error:)];
}
- (void)displayResultWithTicket:(GTLServiceTicket *)ticket finishedWithObject:(GTLDriveFileList *)response error:(NSError *)error
{
if (error == nil)
{
NSMutableString *filesString = [[NSMutableString alloc] init];
if (response.files.count > 0)
{
for (GTLDriveFile *file in response.files)
{
[filesString appendFormat:#"%# (%#)\n", file.name, file.identifier];
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/drive/v3/files/%#?key=%#", file.identifier,kClientID];
GTMSessionFetcher *fetcher = [_service.fetcherService fetcherWithURLString:url];
[fetcher beginFetchWithCompletionHandler:^(NSData *datav, NSError *error)
{
if (error == nil)
{
NSLog(#" file web link%#",file.webViewLink);
NSLog(#"file extension%#",file.fileExtension);
NSLog(#"Retrieved file content%#",datav);
NSString *prefixString = #"EMR File";
NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString] ;
NSString *uniqueFileName = [NSString stringWithFormat:#"%#_%#", prefixString, guid];
NSString *filePath = [[NSString alloc]init];
/***************** save the file in document directory ***********************/
if (datav!=nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//Get the docs directory
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *folderPath = [documentsDirectoryPath stringByAppendingPathComponent:#"emrFiles"]; // subDirectory
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath])
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:NO attributes:nil error:nil];
//Add the FileName to FilePath
filePath = [folderPath stringByAppendingPathComponent:[uniqueFileName stringByAppendingFormat:#".%#",file.fileExtension]];
//Write the file to documents directory
[datav writeToFile:filePath atomically:YES];
}
}
else
{
NSLog(#"An error occurred: %#", error.localizedDescription);
}
}];
}
}
else
{
[filesString appendString:#"No files found."];
}
}
else
{
[self showAlert:#"Error" message:error.localizedDescription];
}
}
the file details like
NSLog(#" file web link%#",file.webViewLink);
NSLog(#"file extension%#",file.fileExtension);
file.fileExtension
These are getting null in all the time
However I am getting value for
file.name
file.identifier
Finally if I try to download a file using this url
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/drive/v3/files/%#?key=%#", file.identifier,kClientID];
and
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/drive/v3/files/%#?key=My API key from google console",
myfile.identifier];
I am getting nsdata very small content
Printing description of datav:
<7b0a2022 6b696e64 223a2022 64726976 65236669 6c65222c 0a202269
64223a20 22304236 6a6e576c 46497868 434f566e 6c586546 4a496344
526d596d 68694e44 6c735432 557a516b 7057566c 70716431 5246222c
0a20226e 616d6522 3a202253 41544859 412e646f 6378222c 0a20226d
696d6554 79706522 3a202261 70706c69 63617469 6f6e2f76 6e642e6f
70656e78 6d6c666f 726d6174 732d6f66 66696365 646f6375 6d656e74
2e776f72 6470726f 63657373 696e676d 6c2e646f 63756d65 6e74220a 7d0a>
Because of getting null value of file extension I tried with giving static extension and saved it in directory and try to view it and I get this error
“ File_B85DABFF-BCA5-4B5E-8FDC-59D2907F0509-1053-000003B0E6E4C9A9.docx” can’t be opened for some reason.
I don't know that where I am lacking I have searched more but could not help please any one help me on this
thanks in advance

PubNub local messages duplicating?

For my pubnub chat app, I am storing some messages locally to keep it from using tons of wifi/data. It seems to work fine, but sometimes the last message is duplicated. Here is my saving,loading,reloading code.
#pragma mark - PubNub manager methods
- (NSString *)parseMessage:(id)message
{
if ([message isKindOfClass:[NSDictionary class]]) {
NSDictionary *messageAsDict = message;
if ([[messageAsDict objectForKey:#"text"] isKindOfClass:[NSString class]]) {
NSString *messageString = [messageAsDict objectForKey:#"text"];
if (messageString || messageString.length > 0) {
return messageString;
} else {
return #"Unable To Parse Message";
}
} else {
return #"Unable To Parse Message";
}
} else if ([message isKindOfClass:[NSString class]]) {
NSString *messageString = message;
if (messageString.length > 0) {
return messageString;
} else {
return #"Unable To Parse Message";
}
} else {
return #"Unable To Parse Message";
}
}
- (void)saveObjects
{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *messagesDirectoryPath = [docDir stringByAppendingPathComponent:#"Messaging"];
if (![[NSFileManager defaultManager] fileExistsAtPath:messagesDirectoryPath]) {
[[NSFileManager defaultManager] createDirectoryAtPath:messagesDirectoryPath withIntermediateDirectories:YES attributes:nil error:&error];
}
NSString *messagesPath = [messagesDirectoryPath stringByAppendingPathComponent:messageFile];
NSString *timeTokenPath = [messagesDirectoryPath stringByAppendingPathComponent:timeTokenFile];
NSString *timeTokenString = [NSString stringWithFormat:#"%ld", (long)lastTimeToken];
[messagesArray writeToFile:messagesPath atomically:YES];
[timeTokenString writeToFile:timeTokenPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
}
- (void)loadObjects
{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *messagesDirectoryPath = [docDir stringByAppendingPathComponent:#"Messaging"];
NSString *messagesPath = [messagesDirectoryPath stringByAppendingPathComponent:messageFile];
NSString *timeTokenPath = [messagesDirectoryPath stringByAppendingPathComponent:timeTokenFile];
messagesArray = [NSMutableArray arrayWithContentsOfFile:messagesPath];
if (!messagesArray) {
messagesArray = [[NSMutableArray alloc] init];
[self saveObjects];
}
NSString *timeTokenString = [NSString stringWithContentsOfFile:timeTokenPath encoding:NSUTF8StringEncoding error:&error];
if (![timeTokenString isEqualToString:#""]) {
lastTimeToken = [timeTokenString integerValue];
} else {
lastTimeToken = [self currentTimeToken];
[self saveObjects];
}
}
- (void)reloadMessages
{
messagesArray = [[NSMutableArray alloc] init];
//Get all the chats you missed
[self.pnClient historyForChannel:kCHAT_CHANNEL withCompletion:^(PNHistoryResult *result, PNErrorStatus *status) {
// Check whether request successfully completed or not.
if (!status.isError) {
// Handle downloaded history using:
// result.data.start - oldest message time stamp in response
// result.data.end - newest message time stamp in response
// result.data.messages - list of messages
// Get messages
for (id message in result.data.messages) {
[messagesArray addObject:[self parseMessage:message]];
}
// Set timetoken
lastTimeToken = [self parsePNTimeToken:result.data.end];
// Save stuff
[self saveObjects];
dispatch_async(dispatch_get_main_queue(), ^{
[self.messagesTable reloadData];
[self scrollToBottom];
});
} else {
// Request processing failed.
UIAlertController *errorController = [UIAlertController alertControllerWithTitle:#"Error" message:#"Could not recieve messages" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *retryAction = [UIAlertAction actionWithTitle:#"Retry" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[status retry];
}];
[errorController addAction:cancelAction];
[errorController addAction:retryAction];
[self presentViewController:errorController animated:YES completion:nil];
}
}];
}
- (void)addMessage:(PNMessageResult *)message
{
[messagesArray addObject:[self parseMessage:message.data.message]];
lastTimeToken = [message.data.timetoken integerValue] + 1;
[self saveObjects];
}
- (NSInteger)parsePNTimeToken:(NSNumber *)timeToken
{
return trunc([timeToken integerValue] / pow(10, 7));
}
- (NSInteger)currentTimeToken
{
return [[NSDate date] timeIntervalSince1970];
}
- (void)updateLostMessages
{
[self.pnClient historyForChannel:kCHAT_CHANNEL start:[NSNumber numberWithInteger:lastTimeToken] end:[NSNumber numberWithInteger:[self currentTimeToken]] limit:NSIntegerMax withCompletion:^(PNHistoryResult *result, PNErrorStatus *status) {
NSArray *tempResultArray = result.data.messages;
for (id message in tempResultArray) {
[messagesArray addObject:[self parseMessage:message]];
NSLog(#"%#", [self parseMessage:message]);
}
lastTimeToken = [self currentTimeToken] + 1;
[self saveObjects];
[self loadObjects];
dispatch_async(dispatch_get_main_queue(), ^{
[self.messagesTable reloadData];
[self scrollToBottom];
});
}];
}
These methods are pretty straightforward. the parseMessage: one takes a message from whatever and parses the text to be displayed. The saveObjects saves the timeToken and the messages to the disk, and load loads them. The timetoken methods just convert PN timetokens to a less precision format and get the current time token. The updateLostMessages gets all messages from the last messages timetoken to current, and to not get all the messages.
In viewDidLoad I call [self loadObjects] and then [self updateLostMessages] problem is that messages are duplicating! Help appreciated. Also, sorry for long code.
Haha, silly me. I just forgot a + 1 in the reload method. Well, for anyone who wants to use this code to locally store messages instead of getting all of them, here you go. This code stores a timetoken of the last message (+1), and gets all messages from x time token to now.

Working with delegates synchronously

In the below code, self.theFiles prints the null. Because after calling [self.restClient loadMetadata:#"/"], getFiles method keeps working.
I want getFiles method to wait until [self.restClient loadMetadata:#"/"] finishes to get file list and put the data to self.theFiles object. But after [self.restClient loadMetadata:#"/"], getFiles keeps working.
#synthesize theFiles;
- (void)getFiles:(CDVInvokedUrlCommand*)command
{
if (![[DBSession sharedSession] isLinked]) {
[[DBSession sharedSession] linkFromController:self];
}
else
{
[self.restClient loadMetadata:#"/"];
}
NSLog(self.theFiles); //Prints null
NSLog(#"Finished");
}
#pragma mark DBRestClientDelegate methods
- (void)restClient:(DBRestClient*)client loadedMetadata:(DBMetadata*)metadata {
NSArray* validExtensions = [NSArray arrayWithObjects:#"txt", #"text", nil];
NSMutableArray* newPhotoPaths = [NSMutableArray new];
for (DBMetadata* child in metadata.contents) {
self.theFiles=child.path;
NSString* extension = [[child.path pathExtension] lowercaseString];
if (!child.isDirectory && [validExtensions indexOfObject:extension] != NSNotFound) {
[newPhotoPaths addObject:child.path];
}
}
NSLog(self.theFiles); //Prints the file list
}
Output:
null
Finished
/file1.txt
/file2.txt
..... the file list in my dropbox
Is it possible to work my getFiles method with delegate synchronously?
UPDATE
I updated my code. I want to lock the thread using NSLock but doesn't work. The same result.
#synthesize theFiles;
- (void)getFiles:(CDVInvokedUrlCommand*)command
{
if (![[DBSession sharedSession] isLinked]) {
[[DBSession sharedSession] linkFromController:self];
}
else
{
if ([self.theLock tryLock]) {
[self.restClient loadMetadata:#"/"];
NSLog(self.theFiles); //Prints null
NSLog(#"Finished");
}
}
}
#pragma mark DBRestClientDelegate methods
- (void)restClient:(DBRestClient*)client loadedMetadata:(DBMetadata*)metadata {
NSArray* validExtensions = [NSArray arrayWithObjects:#"txt", #"text", nil];
NSMutableArray* newPhotoPaths = [NSMutableArray new];
for (DBMetadata* child in metadata.contents) {
self.theFiles=child.path;
NSString* extension = [[child.path pathExtension] lowercaseString];
if (!child.isDirectory && [validExtensions indexOfObject:extension] != NSNotFound) {
[newPhotoPaths addObject:child.path];
}
}
NSLog(self.theFiles); //Prints the file list
[self.theLock unlock];
}

accessing data from s3 using xcode

I am not quite sure how to download data from S3 with XCode. Any help on how to do this would be greatly appreciated. I have tried the following code to access an image from S3,
AmazonCredentials *cred = [[Amazon alloc] initWithAccessKey:accessKey withSecretKey:secretAccessKey];
AmazonS3Client *s3 = [[AmazonS3Client alloc] initWithCredentials:cred];
S3GetObjectRequest *s3Request = [[S3GetObjectRequest alloc] initWithKey:urlPath withBucket:bucket];
s3Request.delegate = self;
S3GetObjectResponse *s3Response = [s3 getObject:s3Request];
NSData*data = s3Response.body;
image = [UIImage imageWithData:data];
When I run the program, I get the exception "EXC_BAD_ACCESS (code = 2, address = 0x0)." I am also unsure about what exactly to include in the bucket name. Should the bucket string be just "nameOfBucket"? or something like "topLevelFolder/nameOfBucket"? Also, what specifically should be included in the "urlPath"? I think that my exception probably has to do with incorrect bucket and urlPath names.
EDIT: I found that we weren't getting any data from S3 and the solution was to remove the line that said "s3Request.delegate = self;".
Here are two helper methods for getting image and checking if image exists
#import <AWSiOSSDK/S3/AmazonS3Client.h>
+(NSData *)getImage:(NSString *)imageID inFolder:(NSString *)folderName
{
// Initial the S3 Client.
//folderName = bucket name
AmazonS3Client *s3 = [[AmazonS3Client alloc] initWithAccessKey:ACCESS_KEY_ID withSecretKey:SECRET_KEY];
s3.timeout = 1000;
#try {
NSString *pictName = [NSString stringWithFormat:#"%#%#", imageID, #".jpg"];
S3GetObjectRequest *porr = [[S3GetObjectRequest alloc] initWithKey:pictName withBucket:folderName];
// Get the image data from the specified s3 bucket and object.
S3GetObjectResponse *response = [s3 getObject:porr];
NSData *imageData = response.body;
return imageData;
}
#catch (AmazonClientException *exception) {
return nil;
}
}
+(BOOL)isImageExists:(NSString *)imageID inFolder:(NSString *)folderName
{
#try {
AmazonS3Client *s3 = [[AmazonS3Client alloc] initWithAccessKey:ACCESS_KEY_ID withSecretKey:SECRET_KEY];
NSString *pictName = [NSString stringWithFormat:#"%#%#", imageID, #".jpg"];
NSLog(#"Start checking a full size image %#", imageID);
S3GetObjectMetadataRequest *porr = [[S3GetObjectMetadataRequest alloc] initWithKey:pictName withBucket:folderName];
S3GetObjectResponse *response = [s3 getObjectMetadata:porr];
if(response)
{
return YES;
}
}
#catch (AmazonServiceException *ex) {
NSLog(#"AmazonServiceException in isImageExists %#", ex.description);
return NO;
}
#catch (NSException *exception) {
NSLog(#"NSException in isImageExists %#", exception.description);
return NO;
}
return NO;
}
Assigning a delegate s3Request.delegate = self; causes the AmazonS3Client to send messages to the delegate methods (AmazonServiceRequestDelegate) and preempts messages to S3GetObjectResponse
The two most common delegate methods are:
-(void)request:(AmazonServiceRequest *)request didCompleteWithResponse:(AmazonServiceResponse *)response
-(void)request:(AmazonServiceRequest *)request didFailWithError:(NSError *)error

IOS: HTTPRequest to download a pdf file

I have a problem in my app.
I'm using ASIHttpRequest to download a pdf file with this code:
- (void) downloadPdf{
AppDelegate *appDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
if (currentDownload) {
[currentDownload clearDelegatesAndCancel];
currentDownload = nil;
totalWorker = 0;
[workers release]; workers = nil;
progressView.progress = 0.0;
} else {
[self removeFile];
appDelegate.alertGlobal = [[UIAlertView alloc] initWithTitle: #"Download file..."
message: #""
delegate: self
cancelButtonTitle: #"Annul"
otherButtonTitles: nil];
progressView = [[UIProgressView alloc] initWithFrame:
CGRectMake(30.0f, 43.0f, 225.0f, 10.0f)];
[appDelegate.alertGlobal addSubview:progressView];
[progressView setProgressViewStyle: UIProgressViewStyleBar];
[appDelegate.alertGlobal show];
NSString *tmp = #"http://192.168.0.13:8888/file.pdf";
currentDownload = [[HappyDownload alloc] initWithURL:[NSURL URLWithString:tmp]];
currentDownload.numberOfWorkers = totalWorker;
currentDownload.totalChunk = 1;
currentDownload.delegate = self;
currentDownload.downloadProgressDelegate = self;
currentDownload.allowResumeForFileDownloads = YES;
documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
[currentDownload setDownloadDestinationPath:[documentsDirectory stringByAppendingPathComponent:#"file.pdf"]];
[workers removeAllObjects];
[currentDownload startAsynchronous];
start = [NSDate new];
}
}
- (void) removeFile{
NSString *pathTemp = [NSHomeDirectory()stringByAppendingPathComponent:#"Documents"];
//NSString *path = [pathTemp stringByAppendingPathComponent:#"file.pdf"];
NSFileManager* fm = [[[NSFileManager alloc] init] autorelease];
NSDirectoryEnumerator* en = [fm enumeratorAtPath:pathTemp];
NSError* err = nil;
BOOL res;
NSString* file;
while (file = [en nextObject]) {
res = [fm removeItemAtPath:[pathTemp stringByAppendingPathComponent:file] error:&err];
if (!res && err) {
NSLog(#"error: %#", err);
}
}
}
-(void)requestFinished:(ASIHTTPRequest *)request{
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSSecondCalendarUnit
fromDate:start
toDate:[[NSDate new] autorelease]
options:0];
int duration = [comps second];
NSLog(#"request finished, duration:%d", duration);
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
appDelegate.downloaded = TRUE;
[currentDownload clearDelegatesAndCancel];
currentDownload = nil;
totalWorker = 0;
[workers release]; workers = nil;
progressView.progress = 0.0;
[appDelegate.alertGlobal dismissWithClickedButtonIndex:0 animated:YES];
[appDelegate.alertGlobal release];
downloadedFirstTime = TRUE;
NSError *error;
NSString *pathTemp = [NSHomeDirectory()stringByAppendingPathComponent:#"Documents"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSLog(#"Documents directory: %#", [fileManager contentsOfDirectoryAtPath:pathTemp error:&error]);
[self openFile];
}
- (void) requestFailed:(ASIHTTPRequest *)request{
AppDelegate *appDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
[currentDownload clearDelegatesAndCancel];
currentDownload = nil;
totalWorker = 0;
[workers release]; workers = nil;
progressView.progress = 0.0;
[appDelegate.alertGlobal dismissWithClickedButtonIndex:0 animated:YES];
[appDelegate.alertGlobal release];
NSLog(#"request failed");
NSLog(#"Error %#", [request error]);
int statusCode = [request responseStatusCode];
NSString *statusMessage = [request responseStatusMessage];
NSLog(#"statuscode:%d", statusCode);
NSLog(#"statusmessage:%#", statusMessage);
}
OK in this way I download correctly a pdf file and I open it in this way with this control:
https://github.com/vfr/Reader
the classic controller to open pdf file in iPhone and I use this method:
- (void) openFile{
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
NSString *phrase = nil; // Document password (for unlocking most encrypted PDF files)
NSString *pathTemp = [NSHomeDirectory()stringByAppendingPathComponent:#"Documents"];
NSString *path = [pathTemp stringByAppendingPathComponent:#"file.pdf"];
assert(path != nil); // Path to last PDF file
ReaderDocument *document = [ReaderDocument withDocumentFilePath:path password:phrase];
if (document != nil) // Must have a valid ReaderDocument object in order to proceed
{
readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];
readerViewController.delegate = self; // Set the ReaderViewController delegate to self
//mainWindow.rootViewController = readerViewController; // Set the root view controller
}
[self presentModalViewController:readerViewController animated:YES];
[readerViewController release];
}
It work fine the FIRTS TIME and I open a first file pdf without problems, but when I download a second different pdf that I upload on the server, I have a big problem...inside it I see two pdf file, one above the other, but I don't understand if the problem is the ASIHttpRequest or the readerViewController. As you can see I remove file inside HomeDirectory but I don't understand the problem, can you help me?
thanks
At your remove method, have you checked the path(with file name) is correct? Also, try one more thing the place where you delete your file,after that check for existence of that file.
May be it give some idea.

Resources