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.
Related
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];
}
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];
I am new to ios,so inorder to get accesstoken, i followed the link
http://technogerms.com/login-with-google-using-oauth-2-0-for-ios-xcode-objective-c/ .so in these link they used json.h files are they mandatory.if it is yes then explain me about json github in these link.
Here is the link what you want.
https://github.com/johnezang/JSONKit
Use native NSJSONSerialization class, you can find more info on below link,
iOS NSJSONSerialization
How to use NSJSONSerialization
There is no compulsory to use JSON.h in your project. Now You can use inbuilt apple JSON parser. IF you want to download JSon library then link is
Download JSon file from here
Otherwise you can use this Inbuilt apple JSON Parser by using following method.
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves || NSJSONReadingMutableContainers error:&myError];
The full code is as below:
NSString *urlString=[NSString stringWithFormat:#"%#listcontact.php?uid=%#&page=0",LocalPath,appdel.strid]; //---- Add your URL for webservice-----
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
There are two NSURLConnection request methods AsynchronousRequest and SynchronousRequest.
(1) For AsynchronousRequest
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSError *error1;
NSDictionary *res=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
}];
(2) For SynchronousRequest
NSData *GETReply = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves error:&myError];
i am trying to load the data from an online link that works with php. The link returns an xml.
That xml i want to save in the Documents Directory from the iPad.
I am trying this:
NSString *post = #"";
NSData *postData = [post dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:NO];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[urlRequest setURL:[NSURL URLWithString:#"http://www.test.be/tools/xml_nieuwsbrief.php"]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if(!urlData) {
NSLog(#"No connection!");
}
NSLog(#"Receive:%d bytes",[urlData length]);
NSString *aStr = [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"________%#", aStr);
the string does return - null -, i a have been searching the internet, but does not find anything that can lead me to my problem.
Can someone help me for letting me see what i am doing wrong?
Thanks in advance,
Snowy
I'd check the status code of the response object (change the NSURLResponse object into an NSHTTPURLResponse and you'll have a statusCode property available).
If you are actually getting - null - out of the NSData-response you should probably be looking at the server-side script. Perhaps it is not expecting an empty POST-request?
Is there a way to verify / validate a remote XML (or download it first and store it locally) before processing it and store the info into CoreData or DB with iPhone SDK 3?
In Cocoa you can just download it
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error = nil;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
and load it into a NSXMLDocument
NSXMLDocument *doc = [[NSXMLDocument alloc]
initWithData:urlData options:0 error:&error];
and get the nodes with
NSArray* tempArray = [doc nodesForXPath:#"something/anotherthing" error:&error];
Don't know if all of this works on the iPhone.