0
votes

I'm trying to create an iPhone File downloader using AFNetworking 2.0 (https://github.com/AFNetworking/AFNetworking)

I'm getting random issues with this code:

-(void)downloadFile:(NSString *)UrlAddress
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:UrlAddress]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    NSString *documentsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *mp3Name = @"lol.mp3";
    NSString *path = [NSString stringWithFormat:mp3Name,documentsDir];

    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 setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

        NSLog(@"Download = %f", (float)totalBytesRead / totalBytesExpectedToRead);

    }];
    [operation start];
}

When I call this function, I randomly get this:

Successfully downloaded file to ... -> SO IT WORKS

Error Domain=NSURLErrorDomain Code=-1017 "cannot parse response" -> SO DOWNLOAD IS A SUCCESS but program tell us that there's a problem

Error Domain=NSPOSIXErrorDomain Code=13 "The operation couldn’t be completed. Permission denied" -> SO NOTHING IS DOWNLOADED and this one happens most of the time.

I can't find anything related to these issues on the web and this is really annoying since it's happening randomly.

Thanks for your help and have a good day.

1
Nothing related on the web to NSPOSIXErrorDomain code 13? Looks like this could be a server-side issue. Something port-related to your URL perhaps? google.com/search?q=nsposixerrordomain%20code%2013&rct=j - Aaron

1 Answers

1
votes

My first impression is that you are retrieving the document directory incorrectly.

NSString *documentsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *mp3Name = @"lol.mp3";
NSString *path = [NSString stringWithFormat:mp3Name,documentsDir];

If you look at this code, the path will be: lol.mp3 Since this is not a valid path your download will fail.

The way it should be done is:

NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *mp3Name = @"lol.mp3";
NSString *path = [documentsDir stringByAppendingPathComponent:mp3Name];