I am performing a download through NSURLConnection class and updating a progress bar view according to the received bytes in the NSURLConnection delegate connection didReceiveData.
Everything is working fine when I am on the page where downloading is happening but when I am going to some other view controller and coming back to my downloading page, the connection delegate functions are being called while transition of page but coming back does not upgrade the progress bar.
The code I am using is:
- (IBAction)download:(id)sender {
_currentURL = [NSString stringWithFormat:#"url_to_download"];
NSURL *url =[NSURL URLWithString:_currentURL];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
_receivedData = [[NSMutableData alloc]initWithLength:0];
connection2 = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(#"THE STATUS CODE IS %d",[httpResponse statusCode]);
statuscode = [httpResponse statusCode];
NSLog(#"into didReceiveResponse");
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[_receivedData setLength:0];
expectedBytes = [response expectedContentLength];
NSLog(#"EXPECTED BYTES:%ld",expectedBytes);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"into did receivedata");
[_receivedData appendData:data];
self.setting.enabled = NO;
float progressive = (float)[_receivedData length] / (float)expectedBytes;
[self.progress setProgress:progressive];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
AppDelegate *app = (AppDelegate*) [[UIApplication sharedApplication]delegate];
NSLog(#"into didfailwitherror");
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"connection failed");
}
-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.setting.enabled = YES;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"DOCUMENT DIRECTORY :%#",documentsDirectory);
_imagePath = [documentsDirectory stringByAppendingPathComponent:_fullPath];
NSLog(#"iamge path:%#",_imagePath);
NSLog(#"succeeded");
[UIApplication sharedApplication].networkActivityIndicatorVisible= NO;
NSLog(#"Succeeded! Received %d bytes of data",[_receivedData length]);
// flag= [_receivedData writeToFile:imagePath atomically:NO];
if([_receivedData writeToFile:_imagePath atomically:YES])
{
NSLog(#"write successfull");
app.dl_status = 0;
[HUD hide:YES];
[HUD removeFromSuperview];
HUD = nil;
[self completedDownloadHUD];
[self.download setBackgroundImage:[UIImage imageNamed:#"download.png"] forState:UIControlStateNormal];
}
else{
app.dl_status = 0;
NSLog(#"write failed");
[HUD hide:YES];
[self errorDownloadHUD];
}
NSString *imagePathExtension;
imagePathExtension = [_imagePath pathExtension];
if([imagePathExtension isEqual:#"jpg"])
{
NSLog(#"imagepathextension is jpg");
UIImage *img =[UIImage imageWithContentsOfFile:_imagePath];
UIImageWriteToSavedPhotosAlbum(img, self, #selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
else if([imagePathExtension isEqual:#"mov"])
{
NSLog(#"imagepathextension is mp4");
UISaveVideoAtPathToSavedPhotosAlbum(_imagePath, nil, nil, nil);
}
}
Please tell me how i can retain the value of progress bar while coming back to page and update it.
Change your delegate to this then update the question. I suspect you will find something gets hit with the asserts:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"into didReceiveData");
[_receivedData appendData:data];
assert(_receivedData); // it exists
assert([_receivedData length]); // it also has some data in it
self.setting.enabled = NO;
float progressive = (float)[_receivedData length] / (float)expectedBytes;
assert(expectedBytes > 0);
assert(progressive > 0 && progressive <= 1);
assert(self.progress);
assert(!self.progress.hidden);
assert(!self.progress.alpha > 0.5);
assert(self.progress.window);
[self.progress setProgress:progressive];
}
If you don't get any asserts, you still are getting delegate messages, and the progress bar is not visible (or not moving) then log the value of progressive and/or the progress bar frame.
Related
I have use this code for download pdf in iPhone on button click are as:-
- (IBAction)download:(id)sender {
self.downloadedMutableData = [[NSMutableData alloc] init];
urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://www.tutorialspoint.com//objective_c/objective_c_tutorial.pdf"]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60.0];
self.connectionManager = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
}
#pragma mark - Delegate Methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"%lld", response.expectedContentLength);
self.urlResponse = response;
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.downloadedMutableData appendData:data];
progress.progress = ((100.0/self.urlResponse.expectedContentLength)*self.downloadedMutableData.length)/100;
if (progress.progress == 1) {
progress.hidden = YES;
} else {
progress.hidden = NO;
}
float percentage=((100.0/self.urlResponse.expectedContentLength)*self.downloadedMutableData.length);
percentageLbl.text = [NSString stringWithFormat:#"%.0f%%",percentage];
NSLog(#"%.0f%%",percentage);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Finished");
if (self.downloadedMutableData)
{
NSString *filePath = [NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"Pdf.pdf"];
[self.downloadedMutableData writeToFile:filePath atomically:YES];
}
}
I don't know where my pdf file is save in iPhone. I want to save pdf file in Gallery in iPhone.
Can you help me?
i am newbie in iOS make an app that contain JSON Parsing data for that i use NSURLConnection and fetch data but here my URL Contain Pagination so, i want to fetch pagination data when tableView scroll for that i write a code like as
- (void)viewDidLoad
{
page=0;
NSString *path = [NSString stringWithFormat:#"http://isp.ebizzprojects.com/webservices/testimonial.php?page=%d",page];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
And Also I send second request when my table view scroll like as
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSInteger currentOffset = scrollView.contentOffset.y;
NSInteger maximumOffset = scrollView.contentSize.height- scrollView.frame.size.height;
if (maximumOffset - currentOffset <= 0)
{
page = page + 1;
[self getData];
}
}
-(void)getData
{
NSString *path = [NSString stringWithFormat:#"http://isp.ebizzprojects.com/webservices/testimonial.php?page=%d",page];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
And NSURLConnection delegate method like as
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[_parsedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_parsedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
_parsedData = nil;
_parsedData = [[NSMutableData alloc]init];
[[[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Connection Error" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil]show];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString =[[NSString alloc]initWithData:_parsedData encoding:NSUTF8StringEncoding];
NSDictionary *loDict = [responseString JSONValue];
self.responceArray=[loDict valueForKey:#"description"];
self.nameArray=[loDict valueForKey:#"name"];
self.testimonialTable.hidden=FALSE;
[self.testimonialTable reloadData];
}
From this my code when i scroll table view then i got only second page data i want to keep both data in to my table view when my tableview scroll please give me solution for this.
Thanks.
You need to add new items to array like, create NSMutableArray for self.responceArray and self.nameArray
[self.responceArray addObjectsFromArray:[loDict valueForKey:#"description"]];
[self.nameArray addObjectsFromArray:[loDict valueForKey:#"name"]];
I am working on a web service app and i have a question. I am calling a specific Url site with the following code:
NSURL *Url = [NSURL URLWithString:[requestStream stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *htmlString = [NSString stringWithContentsOfURL:Url encoding:NSUTF8StringEncoding error:&error];
Then i create an nsstring and print it with the NSLog and i got the following results:
2014-05-14 15:50:58.118 jsonTest[1541:907] Data : Array
(
[url] => http://sheetmusicdb.net:8000/hnInKleinenGruppen
[encoding] => MP3
[callsign] => SheetMusicDB.net - J
[websiteurl] =>
)
My question in how can i parse the URL link and then use it as a value? I tried to put them to an array or a dictionary but i get error back. So if anyone can help me i would appreciate it.
Ok i managed to grab the link with the following code:
if(htmlString) {
//NSLog(#"HTML %#", htmlString);
NSRange r = [htmlString rangeOfString:#"=>"];
if (r.location != NSNotFound) {
NSRange r1 = [htmlString rangeOfString:#"[encoding]"];
if (r1.location != NSNotFound) {
if (r1.location > r.location) {
_streamTitle = [htmlString substringWithRange:NSMakeRange(NSMaxRange(r), r1.location - NSMaxRange(r))];
NSLog(#"Title %#", _streamTitle);
}
}
}
} else {
NSLog(#"Error %#", error);
}
Thank you for your suggestions. My problem now is that i pass the string into an avplayer and i can't hear music.
I think this will be help for you..
// #property (nonatomic,retain) NSMutableData *responseData;
// #synthesize responseData;
NSString *urlString=#"http:your urls";
self.responseData=[NSMutableData data];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self];
NSLog(#"connection====%#",connection);
JSON Delegates :
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
self.responseData=nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray *response_Array = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];
// Write code for retrieve data according to your Key.
}
Try This:
NSString *urlStr=[NSString stringWithFormat:#"uRL"];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
if (theConnection)
{
receivedData=[[NSMutableData data] retain] ;
}
#pragma mark - Connection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// append the new data to the receivedData
// receivedData is declared as a method instance elsewhere
//NSLog(#"data %#",data);
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// release the connection, and the data object
// [connection release];
// [receivedData release];
UIAlertView *prompt = [[UIAlertView alloc] initWithTitle:#"Connection Failed" message:[error localizedDescription]delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[prompt show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *content = [[NSString alloc] initWithBytes:[receivedData bytes]
length:[receivedData length] encoding: NSUTF8StringEncoding];
NSData *jsonData = [content dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
}
I am beginner in IOS programming. My question is my app fetching data from JSON in my web server, when starting the apps, it is slightly lag and delay due to the fetching process, so i would like to show activity indicator when i connecting to JSON data. How can i do that?
My JSON coding:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *urlAddress = [NSURL URLWithString:#"http://emercallsys.webege.com/RedBoxApp/getEvents.php"];
NSStringEncoding *encoding = NULL;
NSError *error;
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:&error];
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
eventsDetail = [[dict objectForKey:#"eventsDetail"] retain];
}
[jsonreturn release];
}
use the following code
//add a UIActivityIndicatorView to your nib file and add an outlet to it
[indicator startAnimating];
indicator.hidesWhenStopped = YES;
dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
//Load the json on another thread
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:NULL];
[jsonreturn release];
//When json is loaded stop the indicator
[indicator performSelectorOnMainThread:#selector(stopAnimating) withObject:nil waitUntilDone:YES];
});
You can use something like below code:
- (void)fetchData
{
[activityIndicator startAnimating];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *theRequest = [[NSURLRequest alloc]initWithURL:url];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection) {
}
else {
NSLog(#"The Connection is NULL");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
webData = [[NSMutableData data] retain];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction %#",error);
UIAlertView *connectionAlert = [[UIAlertView alloc] initWithTitle:#"Information !" message:#"Internet / Service Connection Error" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[connectionAlert show];
[connectionAlert release];
[connection release];
[webData release];
return;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
//NSLog(#"Received data :%#",theXML);
//[theXML release];
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary: webData error:&error];
if (dict) {
eventsDetail = [[dict objectForKey:#"eventsDetail"] retain];
}
[activityIndicator stopAnimating];
}
i am using NSURLConnection to download mp3 files from server, my code is
- (IBAction)download:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://viadj.viastreaming.net/start/psalmsmedia/ondemand/Nin%20snehamethrayo.mp3"];
NSLog(#"%#", url);
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
receivedData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
}
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [[paths objectAtIndex:0]stringByAppendingPathComponent:#"myFile.mp3"];
[receivedData writeToFile:documentsDirectoryPath atomically:YES];
[connection release];
}
when i click download button, the activity indicator start animating and stops after some time (i think it is downloading). but after that i can't find the downloaded file on my iPhone disk. actually where those files stored after downloading.
i have edited my info.plist to support iTunes file sharing.
is their any mistake with this code? or why can't i see the downloaded files?
My Created one class for downloading ringtones, See first RingtoneDwonloader.h file
import
#protocol RingtoneDownloaderDelegate
-(void)downloadingCompleted;
#end
#interface RingtoneDownloader : NSObject
{
NSMutableData *receivedData;
NSDate *connectionTime;
NSMutableString *diskPath;
id<RingtoneDownloaderDelegate>delegate;
}
#property(nonatomic, retain) iddelegate;
-(void)createUrlRequestForDownloadRingtone:(NSString *)urlString;
-(void)cancelDownloading;
#end
Now my RingtoneDownloader.m file,
import "RingtoneDownloader.h"
import "AppDelegate.h"
#interface RingtoneDownloader(){
AppDelegate *_appDelegate;
NSURLConnection *theConnection;
}
#end
#implementation RingtoneDownloader
#synthesize delegate;
-(void)createUrlRequestForDownloadRingtone:(NSString *)urlString{
_appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
theConnection =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it
[receivedData setLength:0];
// long responseLength = [response expectedContentLength];
// NSLog(#"%ld", responseLength);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// release the connection, and the data object
[theConnection release];
// receivedData is declared as a method instance elsewhere
[receivedData release];
UIAlertView *alt = [[UIAlertView alloc] initWithTitle:#"" message:[NSString stringWithFormat:#"%#", [error localizedDescription]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alt show];
[alt release];
// inform the user
NSLog(#"Connection failed! Error - %# %#", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
// release the connection, and the data object
_appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *soundFileName = _appDelegate.ringtoneURL;
NSString *soundFileextension = [soundFileName substringFromIndex:([soundFileName length]-3)];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", _appDelegate.ringtoneText, soundFileextension]];
NSData *imageData = (NSData *)receivedData;
NSError *err = nil;
BOOL isWriten = [imageData writeToFile:filePath options:NSDataWritingAtomic error:&err];
if(!isWriten){
NSLog(#"Ringtone not saved %#", [err localizedDescription]);
}
[theConnection release];
[receivedData release];
[delegate downloadingCompleted];
}
-(void)cancelDownloading{
[theConnection cancel];
[theConnection release];
[delegate downloadingCompleted];
}
Now u have to just created and instance of this class and set the delegate that i m create. That delegate give u information regarding your ringtone file is successfully downloaded or not.
Use iTunes file sharing in your app and copy the ringtone file to the app's documents directory.
Set "Application supports iTunes file sharing" to YES in your info.plist
The user can now access the ringtone via itunes and add it to their devices ringtones.