iosiphonecocoa-touch

Sending Data - NSMutableURLRequest


I am sending an e-mail via a PHP script. This works fine using NSMutableURLRequest, but I would like to attach an image to the e-mail as well.

Here's the code I'm using:

    NSMutableURLRequest *request = 
    [[NSMutableURLRequest alloc] initWithURL:
    [NSURL URLWithString:@"http://example.com/email.php"]];

    [request setHTTPMethod:@"POST"];

    NSString*subject = [NSString stringWithFormat:@"Images from %@",[[UIDevice currentDevice] name]];   

    NSString*to = [[NSUserDefaults standardUserDefaults] objectForKey:@"PreferredPrinterEPrint"];   

    NSString *postString = [NSString stringWithFormat:@"to=%@&message=%@&subject=%@",to,@"hi",subject];

    [request setValue:[NSString 
                       stringWithFormat:@"%d", [postString length]] 
    forHTTPHeaderField:@"Content-length"];

    [request setHTTPBody:[postString 
                          dataUsingEncoding:NSUTF8StringEncoding]];

    [[NSURLConnection alloc] initWithRequest:request delegate:self];

I've seen an article here which describes sending images, but I don't know how to combine the two. Could someone be so kind an help me out?

Thank you!


Solution

  • ASIHTTPRequest has a class called ASIFormDataRequest that makes it incredibly easy to post data and includes the ability to attach files with a single line. I highly recommend it.