Search code examples
iphoneasihttprequest

iPhone not downloading file


I have a tested and working php script that pulls from a db and returns as an XML. I have used ASIHTTPRequest to make a POST to the php script successfully. I have looked for online help to get this to work. From what I understand, all the code is solid. It compiles properly, runs without problem, even makes the request without problem. I get no errors. Since I have thoroughly tested and successfully used the php, I assume the break is on the iPhone side.

I do not understand why it does not download the XML file to the specified location. Any insight would be greatly appreciated.

// Create the request
NSURL *url=[[NSURL alloc]initWithString:@"http://localhost:8888/Project/script.php"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url]retain];

// gather *ALL* data present
if ( [txtEmail.text length] > 0 )
    [request setPostValue:txtEmail.text forKey:@"email"];
if ( [txtFName.text length] > 0 )
    [request setPostValue:txtFName.text forKey:@"firstname"];
if ( [txtID.text length] > 0 )
    [request setPostValue:txtID.text forKey:@"id"];
if ( [txtLName.text length] > 0 )
    [request setPostValue:txtLName.text forKey:@"lastname"];

[request setDidFailSelector:@selector(requestFailed:)]; 
[request setDidFinishSelector:@selector(requestDone:)]; 

[request setDownloadDestinationPath:@"/Library/Project/dbInfo.xml"]; 
[request setDelegate:self]; 
[request startSynchronous]; 
[request release];
[url release];

Solution

  • a few points on your code:

    1. Why are you using a POST request to download a file? usually downloading is done via a GET request (if we're talking REST). You could use a simple ASIHTTPRequest + adding your post values as URL-Parameters (+ handle it on the php side accordingly).

    2. you are allocating and retaining your ASIFormDataRequest instance, but only releasing it once -> results in a memory leak. (for every alloc/copy/retain -> release it).

    To answer you question: i think the downloadDestinationPath is wrong (the application has no permissions to write there). Better:

    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [docDir stringByAppendingPathComponent:@"dbInfo.xml"];
    [request setDownloadDestinationPath:path];
    

    Now your "dbInfo.xml" File is saved in the documents folder of your application. If you're running your app in the simulator, you can find the directory at: ~/Library/Application Support/iPhone Simulator/IOS_SDK_VERSION/Applications/APP_UID/Documents

    And: if you implement the downloadProgressDelegate: request:didReceiveBytes: method, you can check if you're actually receiving data:

    -(void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes {
      NSLog(@"received bytes ..") ;
    }