PDA

View Full Version : NSURLConnection - Using POST




iPhoneeeee
Apr 21, 2009, 03:48 PM
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



xinevil
Apr 22, 2009, 12:33 AM
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
You can do it this way:

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 currentDevice] uniqueIdentifier]] dataUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
[tableView reloadData];

The URLEncodeString.h:

//
// 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:

//
// 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)string, NULL, CFSTR("% '\"?=&+<>;:-"), kCFStringEncodingUTF8);

return [result autorelease];
}

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

@end


Hope this helps :)

iPhoneeeee
Apr 22, 2009, 02:11 PM
Thank you very much!