How to Retrieve Multimedia data from Remote server and store document directory using Objective c - iphone

Hi every One I am new to iPhone. I am retrieving data from remote server with using nsurlconnection and json parser..I am downloaded only one file from the server and i stored in documents path. But in my server url number of files are there like (images,audios,video,text files). How to download at a time when app lunch and save it in document directory. And also i want the same file name in documents as the file name in the server.
I have tried these way .
ViewController
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
NSMutableData *responseData;
NSArray *filesCount;
}
#property(nonatomic,retain)NSArray *filesCount;
#property(nonatomic,retain) NSMutableData *responseData;
#end
.m viewController
#import "ViewController.h"
#import "JSON/JSON.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize filesCount,responseData;
- (void)viewDidLoad
{
[super viewDidLoad];
responseData =[[NSMutableData data]retain];
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://XXXXXXX/XXXXX/filesCount.php"]];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"" message:#"DidFailWithError" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSLog(#"response string is %#",responseString);
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
filesCount = [json objectWithString:responseString error:&error];
[responseString release];
NSLog(#"filesCount is %#",filesCount);
if (filesCount==nil) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"" message:#"Json parsing failed" delegate:self cancelButtonTitle:#"ok" otherButtonTitles: nil];
[alert show];
}
else{
NSMutableString *text = [NSMutableString stringWithString:#"\n"];
for (int i = 0; i < [filesCount count]; i++)
[text appendFormat:#"%#\n", [filesCount objectAtIndex:i]];
NSLog(#"text is %s",[text UTF8String]);
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:text ]]];
NSData *addImageData = UIImagePNGRepresentation(img);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSRange lastComma= [text rangeOfString:#"/" options:NSBackwardsSearch];
NSString *requiredSubString = [text substringFromIndex:(lastComma.location+1)];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:requiredSubString];
[fileManager createFileAtPath:savedImagePath contents:addImageData attributes:nil];
NSLog(#"Saved Document dir %#",savedImagePath);
UIAlertView *alert1=[[UIAlertView alloc]initWithTitle:#"" message:#"files are downloaded" delegate:self cancelButtonTitle:#"ok" otherButtonTitles: nil];
[alert1 show];
}
}
Please help me What wrong i mad.

I'm sorry, I really can't read your question very well. From what I see though you might benefit from looking at AFNetworking (https://github.com/AFNetworking/AFNetworking). It simplifies the process of downloading, and is rock-solid.
Look here for a nice tutorial: http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_afnetworking/

Related

iOS - Trying to save a PDF to the device and Load using a Webview

I am fairly new at this and tried to solve this problem for quite some time now. I want to download a file from a url and save it to the document folder on the device. After that I want to load it to a Webview. The webview part seems to work if I copy a file manually but when I save the URL it shows only 5529 bytes saved with the correct file name?
Down the road I will need to tackle loading file from a secure web-server, hence the connection Authenticate methods.
#interface ViewController ()
#end
#implementation ViewController
#synthesize webView;
#synthesize webData;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void)handleDocumentOpenURL:(NSURL *)url
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[webView setUserInteractionEnabled:YES];
[webView loadRequest:req];
}
-(void)loadFileFromDocumentFolder:(NSString *) filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [documentsDirectory stringByAppendingPathComponent:filename];
NSURL *urlPdf = [NSURL fileURLWithPath: file];
[self handleDocumentOpenURL:urlPdf];
}
- (IBAction)btnSave:(id)sender
{
NSString *urlString = #"http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
if (urlConnection)
{
webData = [NSMutableData data];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error !" message:#"Error has occured, please verify internet connection" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
- (IBAction)btnLoad:(UIButton *)sender
{
[self loadFileFromDocumentFolder:#"test.pdf"];
}
#pragma mark - NSURLConnection Delegate Methods
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"did fail");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"did receive data");
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"did receive response");
[webData setLength:0];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
BOOL isSuccessfull;
NSLog(#"did finish loading. Bytes Received: %d", [webData length]);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:#"test.pdf"];
isSuccessfull = [webData writeToFile:pdfPath atomically:YES];
}
#end

How to assign values from NSMutableDictionary to NSArray

I am doing JSON parsing and I want to show my parsed data in a UITableView.
For that, I am trying to assign parsed data from NSMutableDictionary to NSArray to show in the table view but the array returns null.
Here my array returns null value;
NSMutableDictionary *tempDict1;
NSArray *arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
// NSArray *latestrates = [[responseString JSONValue] objectForKey:#"rates"];
[responseString release];
values = [responseString JSONValue];
array = [[NSMutableArray alloc] init];
array = [values valueForKey:#"rates"];
NSLog(#"array values:--> %#",array);
tempDict1 = (NSMutableDictionary *)array;
arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
NSString *subStar = #"=";
NSMutableArray *arrTitle = [[NSMutableArray alloc] init];
NSMutableArray *arrValues = [[NSMutableArray alloc] init];
[arrTitle removeAllObjects];
[arrValues removeAllObjects];
for (int i=0; i<[arr count]-1; i++)
{
[arrTitle addObject:[[arr objectAtIndex:i] substringToIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])-1]];
[arrValues addObject:[[arr objectAtIndex:i] substringFromIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])]];
NSLog(#"arrTitle is:--> %#",arrTitle);
}
tempDict1 = (NSMutableDictionary*)[array objectAtIndex:0];
array = [values valueForKey:#"rates"];
NSLog(#"tempDict--%#",tempDict1);
[arr retain];
[tbl_withData reloadData];
}
Try editing fourth line in connectionDidFinishLoading to
values = [responseString JSONFragments];
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Your data - %#",array);
Now you can get it according to data format.
EDIT
I think you also dont know how to get a webResponse.
So here is a way to get webResponse -
First set XML delegate in your ViewController.h class
and declare a NSMutableData globaly
#interface ViewController : UIViewController<NSXMLParserDelegate>
#property(nonatomic, retain)NSMutableData *responseData;
#end
Now synthesized this responseData in your ViewController.m class
#synthesize responseData = _responseData;
Now you can send request on server in viewDidLoad: method its up to you in which method you want to send it.
-(void)viewDidLoad
{
NSString *urlString = [NSString stringWithFormat:#"http://EnterYourURLHere"];
NSURL *URL = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]init];
[urlRequest setURL:URL];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-type"];
NSURLConnection *urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
if(!urlConnection)
{
[[[UIAlertView alloc]initWithTitle:#"OOoopppssS !!" message:#"There is an error occured. Please check your internet connection or try again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
}
#pragma mark - Parsing delegate methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.responseData = [[NSMutableData alloc]init];
[self.responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Now parse your data here -
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Your data - %#",array);
}

Unable to download file to app directory in iPhone

I am new to iPhone,
I am currently developing an iPhone app and would like to implement the ability to download file from the url. I have created the UIWebView, when i click on download link in the webview download will start and i am saving that file to a specified folder in the documents directory. but i am unable to see my downloaded file.
Here is my code snippet,
//CAPTURE USER LINK-CLICK in UIwebView.
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:DUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
receivedData = [[NSMutableData data] retain];
} else {
NSLog(#"Inform the user that the connection failed.");
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data1
{
[receivedData appendData:data1];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
DirPath=[self MyApplicationDocumentDirectory];
[receivedData writeToFile:DirPath atomically:YES];
UIAlertView* Alert = [[UIAlertView alloc] initWithTitle:#"Download Complete !"
message:nil delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[Alert show];
[Alert release];
// release the connection, and the data object
[connection release];
[receivedData release];
}
Any help will be appriciated.
EDIT:
BOOL success =[[NSFileManager defaultManager] fileExistsAtPath:MyDirPath];
if (success)
{
UIAlertView* innerAlert = [[UIAlertView alloc] initWithTitle:#"Already downloaded."
message:#"Do you want to Downlaod again ?" delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Yes",#"No",nil];
[innerAlert show];
[innerAlert release];
}
where to write this condition ?
EDIT Check whether downloaded file already exits in doc dir before writing(saving) downloaded data like this:
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:DirPath error:nil];
BOOL fileExists = NO;
for(NSString *fileName in dirContents)
{
NSString *filePath = [DirPath stringByAppendingPathComponent:fileName];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
if([receivedData isEqualToData:fileData]) //your receivedData here
{
fileExists = YES;
}
}
if(fileExists)
{
NSLog(#"File exists");
}
else
{
NSLog(#"File does not exists");
}
U forgot provide fileName for writing data:
DirPath=[self MyApplicationDocumentDirectory];
NSString *filePath = [DirPath stringByAppendingPathComponent:#"yourFileName"];
[receivedData writeToFile:filePath atomically:YES];

downloading using NSURLConnection not downloading anything?

i am using NSURLConnection to download mp3 data from the server , my code is here
- (IBAction)downloadData:(id)sender
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *url = [[NSURL alloc] initWithString:#"http://viadj.viastreaming.net/start/psalmsmedia/ondemand/Nin%20snehamethrayo.mp3"];
[request setURL:url];
[url release];
url = nil;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[responseData release];
[connection release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[responseData
length]);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myFile"];
[responseData writeToFile:fileName atomically:YES];
responseData = nil;
self->imageConnection = nil;
}
am little bit confused about the path given to download. when i click download button i shows "Succeeded! Received 1329 bytes of data" but nothing is downloading. need some help. how will we specify the local path of iPhone to store downloaded data?
- (IBAction)downloadData:(id)sender
{
NSURL *url = [[NSURL alloc] initWithString:#"http://viadj.viastreaming.net/start/psalmsmedia/ondemand/Nin%20snehamethrayo.mp3"];
NSMutableURLRequest *theRequest_to = [NSMutableURLRequest requestWithURL:url];
[url release];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:theRequest_to delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response
{
NSString *filepath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"snehamethrayo.mp3"]; // here you can set your filename which you can get from url
[[NSFileManager defaultManager] createFileAtPath:filepath contents:nil attributes:nil];
file = [[NSFileHandle fileHandleForUpdatingAtPath:filepath] retain];// Here file is object of NSFileHandle and its declare in .h File
[file seekToEndOfFile];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[file seekToEndOfFile];
[file writeData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
[file closeFile];
}
No need for any code change I think.Just put an nslog and see...
NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myFile"];
NSLog(#"%#",fileName);
That will list the file location like this
/Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/(your app)/Documents/myFile. ie the downloaded file is in your document folder.
note: don't forget to put the file format ie
NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myFile.mp3"];

XML Parsing - NSXMLParserErrorDomain error 5

I'm trying to parse a XML File. It worked very well - until today...
Here's how I start to parse the XML:
NSString *link = [[NSString alloc] init];
link = #"link_to_xml_file";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:link]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
And here's how I'm using the received data:
- (void)connection:(NSURLConnection *)theConnection
didReceiveData:(NSData *)incrementalData
{
if (data == nil)
data = [[NSMutableData alloc] init];
[data appendData:incrementalData];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",actual]];
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] error:&parseError];
if (parseError != nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[parseError localizedDescription] delegate:nil cancelButtonTitle:#"Zurück" otherButtonTitles:nil];
[alert show];
[alert release];
} //shows an alertview with NSXMLParserErrorDomain error 5
NSLog(#"String: %#",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); //returns null
NSLog(#"Dictionary: %#",xmlDictionary); //returns null
NSMutableDictionary *tempDictForAddDate = [[NSMutableDictionary alloc] initWithDictionary:xmlDictionary];
NSDateFormatter *originalDate = [[NSDateFormatter alloc] init];
[originalDate setDateFormat:#"dd.MM.yyyy"];
NSString *today = [originalDate stringFromDate:[NSDate date]];
[tempDictForAddDate setObject:today forKey:#"updated"];
[tempDictForAddDate writeToFile:filePath atomically:YES];
self.contentList = [[tempDictForAddDate objectForKey:#"xmlObject"] objectForKey:#"event"];
[self sortContent];
}
The XML-File works in my browser. And every tag is closed. There aren't any errors but I never get the data of the file.
I hope someone can help.
mavrick3.
You are (wisely) using asynchronous url connection, but this means your didReceiveData delegate will be called multiple times as the data comes in, so it won't be complete at the point you are parsing it.
You probably want to move the parsing into the following delegate method.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
See Apple's Documentation here
EDIT:
Always a good idea to formally validate your XML - I tend to use the w3c tools http://www.w3schools.com/xml/xml_validator.asp
Also, when things that used to work stop working, I always ask myself what has changed? Is the file different? Is it larger? Are you sure it is present on the server and your browser isn't using a cached version?