xcode & (un)zip file - ios7

I have an problem, I have develop one app where I actually need to unzip file. This files I receive from internet, save on Document folder of device and try to unzip.
But... unzip never occurs. The message I receive is:
Error Domain=SSZipArchiveErrorDomain Code=-1 "failed to open zip file" UserInfo=0xad36430 {NSLocalizedDescription=failed to open zip file}
Also I tried other library... but the result is the same.
The zip file is made by server (so we have no control over this part.) but we know that they use gzip to create this file.
I have already used "search"... but with no luck.
One more important note. If I unzip this file on my mac, than zip it again and point "localFilePath" to this new file, all works fine!. Also, the server guy say that they use this ZIP in other apps with no problems at all.
Any advice where do I need to look?
Thanks
The code:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://......"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(#"File downloaded to: %#", filePath);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *localFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[filePath lastPathComponent]];
NSString *unzipFolder = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"/unzipfolder"];
NSLog(#"localFilePath: %#",localFilePath);
NSLog(#"unzip folder: %#",unzipFolder);
NSError *erro = nil;
[SSZipArchive unzipFileAtPath:localFilePath toDestination:unzipFolder overwrite:YES password:nil error:&erro delegate:self];
NSLog(#"Erro: %#",erro);
}];
[downloadTask resume];

Related

Objective-C send get method with header to download file

in my osx app, I want to download a file from a website, in order to do that, I first tried with NSData dataWithContentsOfURL:url but I'm accessing ot throught an API, so I need to send a token in the header of my GET request so now, my method to download a file is that:
-(void)downloadFile:(NSString*)name from:(NSString*)stringURL in:(NSString*)path{
NSURL *aUrl = [NSURL URLWithString:stringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"GET"];
[request addValue:self.token forHTTPHeaderField:#"Authorization"];
NSLog(#"%#", stringURL);
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if ( data )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#.torrent", path,name];
[data writeToFile:filePath atomically:YES];
}
}
The url loged is the good one. But the data variable is nil and the error one contain an NSURLErrorDomaincode with the code 1002. Referring to the doc:
Returned when a properly formed URL cannot be handled by the framework.
The most likely cause is that there is no available protocol handler for the URL.
So how can I send a GET request with custom headers and then download the file ?
There are some mistakes in your code:
documentsDirectory is not used, so the data can be wrote to nowhere.
The default HTTP method is GET so you do not need to specify it.
You should pass in the full URL: http://api.t411.io/torrents/download/4693572. And I thought you may passed in api.t411.io/torrents/download/4693572 before.
And I recommend you using the NSURLSession API that Apple brings in iOS 7 and OS X v10.9.
// in viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
_config = [NSURLSessionConfiguration defaultSessionConfiguration];
_config.HTTPAdditionalHeaders = #{#"Authorization": self.token};
_session = [NSURLSession sessionWithConfiguration:_config];
}
- (void)downloadFile:(NSString*)name from:(NSString*)stringURL in:(NSString*)path {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLSessionDataTask *task = [_session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
return;
}
if (data) {
// Your file writing code here
NSLog(#"%#", data);
}
}];
[task resume];
}

How to save and retrieve files to apps temp folder in ios

I'm new to IOS development. I'm developing an app which involves downloading files and saving that to apps temp folder and I dont know how to do that my current code is given below
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSLog(#"%#",tmpDirURL);
NSString *myString = [tmpDirURL absoluteString];
for(int i=0;i<responseArray.count;i++){
ASIHTTPRequest *saveUrl = [ASIHTTPRequest requestWithURL:responseArray[i]];
[saveUrl setDownloadDestinationPath:myString];
[request startSynchronous];
}
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:myString error:&error];
NSLog(#"%#",directoryContents);
The response array contain a list of URL for downloading files. I know something wrong with my code but I cant find out that error please help me to solve this problem
I found the solution'
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *htmlFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
[data writeToFile:htmlFilePath atomically:YES];
When downloadDestinationPath is set, the result of this request will be downloaded to the file at this location. If downloadDestinationPath is not set, download data will be stored in memory
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSLog(#"%#",tmpDirURL);
NSString *myString = [tmpDirURL absoluteString];
for(int i=0;i<responseArray.count;i++){
ASIHTTPRequest *saveUrl = [ASIHTTPRequest requestWithURL:responseArray[i]];
[saveUrl setDownloadDestinationPath:[myString stringByAppendingPathComponent:[NSString stringWithFormat:#"%i",i ]]; // for each file set a new location inside tmp
[request startSynchronous];
}
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:myString error:&error];
NSLog(#"%#",directoryContents);

Using AFNetworking to download a pdf from the web in appdelegate and then trying to load that stored pdf in a UIWebview on another page

I am using AFNetworking to download a pdf (that will change on a weekly basis) and save it into the documents directory with this code:
//Get the PDF
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.somewebsiteaddress/CurrentEdition1.pdf"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"CurrentEdition1.pdf"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Successfully downloaded file to %#", filePath);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];
I then want to read that saved file in another section of the app in a UIWebView (after it has downloaded) and use this code:
//Now create Request for the file that was saved in your documents folder
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"CurrentEdition1.pdf"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webVieweedition setUserInteractionEnabled:YES];
[webVieweedition setDelegate:self];
[webVieweedition loadRequest:requestObj];
I have used a few single page pdf documents to test with - loading them up on the server and then seeing if they are downloaded and then viewed when changed. Problem is, this seems to only be working about 50% of the time. I'll put a new file up and sometimes the correct one will be shown in the UIWebView and sometimes it will show the previous one and not the new one. I am waiting until I see the download completed message before I try to go to the UIWebView (although I know clients won't do that, but that's a whole other question). Anyway, I'm new to XCode and have just been a web html guy. This has had my head spinning for two days. Using Storyboards, ARC, XCode 4.6.2.
If i understood right, sometimes you see the same pdfs in app, although you changed them on webserver?May be the reason is cache, try construct request this way, ignoring caching
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.somewebsiteaddress/CurrentEdition1.pdf"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];

Downloading File using AFHTTPRequest Operating isn't working?

This is the code I'm using (from this Stack Overflow question, although it's slightly modified):
NSLog(#"Saving File...");
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[detailDataSourceDict valueForKey:#"filepath"]]];
NSLog(#"This is the link you are downloading: %#",request);
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Successfully downloaded file to %#", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];
I get the NSLog "Successfully downloaded file to /Users/xxxx/Library/Application Support/iPhone Simulator/6.0/Applications/F29C1E99-A277-41DC-8205-6556B6123A85/Documents" but when I open up that folder in Finder, I don't see the file. Is there anything that I am doing wrong? I am not getting errors in my code. Any help would be appreciated, thanks.
Update
I am using the AFNetwork library...
You're setting the download location to the actual Documents Directory, rather than a file in the directory. Update your code to use a specific file within the directory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0]; //filepath to documents directory!
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:[path stringByAppendingPathComponent:#"filename.extension"] append:NO];
Also, I think you may want to be setting the inputStream property rather than the outputStream because you are downloading a file rather that uploading one.

Download video before view Iphone sdk

I am developing an application that requires to play some video.
However I do not want to pack the videos with application. Instead I would like to download videos in the NSDocumentDirectory and then play from there using MPMoviePlayerController.
Anybody any Idea how could I download the video from a url?
Thanx,
Gezim
Try this one:
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setHTTPMethod:#"GET"];
NSError *error;
NSURLResponse *response;
NSString *documentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *videosFolderPath = [documentFolderPath stringByAppendingPathComponent:#"videos"];
//Check if the videos folder already exists, if not, create it!!!
BOOL isDir;
if (([fileManager fileExistsAtPath:videosFolderPath isDirectory:&isDir] && isDir) == FALSE) {
[[NSFileManager defaultManager] createDirectoryAtPath:videosFolderPath attributes:nil];
}
NSData *urlData;
NSString *downloadPath = #"http://foo.com/videos/bar.mpeg";
[request setURL:[NSURL URLWithString:downloadPath]];
urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *filePath = [videosFolderPath stringByAppendingPathComponent:#"bar.mpeg"];
BOOL written = [urlData writeToFile:filePath atomically:NO];
if (written)
NSLog(#"Saved to file: %#", filePath);
Create a NSURLRequest, call [NSURLConnection connectionWithRequest:delegate:] and implement the NSURLConnection delegate methods to receive the data as it is downloaded.