Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8233661
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T18:12:20+00:00 2026-06-07T18:12:20+00:00

I have this bit of code to download an mp3 from the server. All

  • 0

I have this bit of code to download an mp3 from the server. All is set up with Table View parsing a podcast, and the link for the mp3 is the _entry.articleURL. After just a few minutes, the iPhone kills the connection, and I end up with just a small portion of the mp3 downloaded. Any ideas what may be causing this?

-(void)didSelectRowAtIndexPath 
{     RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];

             self.nameit = entry.articleTitle;
             NSURL *url = [NSURL URLWithString:entry.articleUrl];    
             NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
             __block NSURLConnection *connection = [NSURLConnection connectionWithRequest:theRequest delegate:self];

             UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance

             __block UIBackgroundTaskIdentifier background_task; //Create a task object

             background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
                 // This code gets called when your app has been running in the background too long and the OS decides to kill it
                 // You might want to cancel your connection in this case, that way you won't receive delegate methods any longer.
                 [connection cancel];
                 [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
                 background_task = UIBackgroundTaskInvalid; //Set the task to be invalid

                 //System will be shutting down the app at any point in time now
             }];

             self.backgroundTaskIdentifier = background_task;
             if (connection) {
                 receivedData = [[NSMutableData data] retain];
                 self.thetable = tableView;
                 self.thepath = indexPath;
             }
             else {
                 UIAlertView *cancelled = [[UIAlertView alloc] initWithTitle:@"Download Failed" message:@"Please check your network settings, and then retry the download." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                 [cancelled show];
                 [cancelled release];
             }
}

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
progress.hidden = NO;
downloadInProgress = YES;
RSSEntry *entry = [_allEntries objectAtIndex:thepath.row];

self.nameit = entry.articleTitle;
downloadlabel.text = [NSString stringWithFormat:@"%@", nameit];
[thebar addSubview:downloadlabel];
[receivedData setLength:0];
expectedBytes = [response expectedContentLength];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
float progressive = (float)[receivedData length] / (float)expectedBytes;
[progress setProgress:progressive];


}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
UIAlertView *connectionfailed = [[UIAlertView alloc] initWithTitle:@"Download Failed" message:@"Please check your network settings, and then retry the download." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[connectionfailed show];
[connectionfailed release];
progress.hidden = YES;
downloadInProgress = NO;
[downloadlabel removeFromSuperview];
[thetable deselectRowAtIndexPath:thepath animated:YES]; 
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
[connection release];



}

- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return nil;
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[nameit stringByAppendingString:@".mp3"]];
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[receivedData writeToFile:pdfPath atomically:YES];
progress.hidden = YES;
downloadInProgress = NO;
[downloadlabel removeFromSuperview];

[thetable deselectRowAtIndexPath:thepath animated:YES]; 

[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}

The issue is that it seems the connectionDidFinishLoading keeps getting called, even if incomplete. Any thoughts?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T18:12:23+00:00Added an answer on June 7, 2026 at 6:12 pm

    Not sure why you are using beginBackgroundTaskWithExpirationHandler to do this work – its purpose is for a completely different task (doing a bit of work after your app gets moved to the background. Your usage of this while in the foreground is most likely the reason for your problems.

    What I suggest you do is go poking around on github etc for a sample Concurrent NSOperation demo project, and use those to do your asynchronous NSURLConnections.

    Also, you are updating a GUI element in a view in the callbacks. Keep in mind you must be on the main thread do work with UIKit. If you need to update something, just use a block and dispatch it to the main queue to do the updating.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I use this bit of code to feed some data i have parsed from
I have the following bit of code, simply: $(function() { $('a.add-photos-link').live('click', function(e) { $(this).colorbox({
I have been trying to follow this example (download the source code from a
I have this bit of code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data;
i have this bit of code, it limits the Li's to 15 of them
I have this bit of code, public static List<string> GetSentencesFromWords(List<string> words, string fileContents) {
So I have this bit of code for x in range(x1,x2): for y in
ok i got this problem. i have this routes: (code bit change) File:/home/dotcloud/current/config/routes.js exports.routes
its a little bit hard to understand. in the header.php i have this code:
I have a bit of php code like this: $test = <!--my comment goes

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.