NSURLConnection - Using POST

Discussion in 'iOS Programming' started by iPhoneeeee, Apr 21, 2009.

  1. iPhoneeeee
    Expand Collapse
    macrumors newbie

    Joined:
    Apr 21, 2009
    #1
    I have searched, searched and searched without any success, so I am making my first post here. Please be kind and offer some guidance.

    I am looking for example or documentation with discussion on using POST, specifically on topic of sending data to PHP forms and website.

    Please help.

    Thank you
     
  2. xinevil
    Expand Collapse
    macrumors newbie

    Joined:
    Jul 12, 2008
    #2
    You can do it this way:
    PHP:
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.org/file.php"]
                                                               
    cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                           timeoutInterval
    :60.0];
        [
    request setHTTPMethod:@"POST"];
        [
    request setHTTPBody:[[NSString stringWithFormat:@"value1=%@&value2=%@",
                               [
    sessionId URLEncodeString],
                               [[
    UIDevice currentDeviceuniqueIdentifier]] dataUsingEncoding:NSUTF8StringEncoding]];
        [[
    UIApplication sharedApplicationsetNetworkActivityIndicatorVisible:YES];
        
    NSURLConnection *connection = [[NSURLConnection allocinitWithRequest:request delegate:self];
        if (
    connection) {
            
    receivedData = [[NSMutableData dataretain];
        }
        [
    tableView reloadData];
    The URLEncodeString.h:
    PHP:
    //
    //  URLEncode.h
    //
    //  Created by Nicky Gerritsen on 24-03-09.
    //  Copyright 2009 __MyCompanyName__. All rights reserved.
    //

    #import <Foundation/Foundation.h>


    @interface NSString (URLEncode)
    + (
    NSString *)URLEncodeString:(NSString *)string;
    - (
    NSString *)URLEncodeString;
    @
    end
    And URLEncodeString.m:
    PHP:
    //
    //  URLEncode.m
    //
    //  Created by Nicky Gerritsen on 24-03-09.
    //  Copyright 2009 __MyCompanyName__. All rights reserved.
    //

    #import "URLEncode.h"


    @implementation NSString (URLEncode)

    // URL encode a string
    + (NSString *)URLEncodeString:(NSString *)string {
        
    NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)stringNULLCFSTR("% '\"?=&+<>;:-"), kCFStringEncodingUTF8);
        
        return [
    result autorelease];
    }

    // Helper function
    - (NSString *)URLEncodeString {
        return [
    NSString URLEncodeString:self];
    }

    @
    end
    Hope this helps :)
     
  3. iPhoneeeee
    Expand Collapse
    thread starter macrumors newbie

    Joined:
    Apr 21, 2009

Share This Page