Write a post

iOS Sending POST Data to your PHP server

Published Feb 15, 2017

Send data from your iOS app to PHP server

You can copy paste the function below, just change the URL to point to your php script.

To use:
Ceate a string with your POST data and call the function.

NSString *post_data = @"name=rob&color=green";
[self sendData:post_data];

-(void) sendData:(NSString*)post_data {
    
    NSData *postData = [post_data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"ENTER URL HERE"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,
                                                                                          NSURLResponse * _Nullable response,
                                                                                          NSError * _Nullable error) {
        
        NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        
        NSLog(@"%@", json);
      
        }
        
    }];
    
    [task resume];
}

Message me with any questions you may have!

Discover and read more posts from Rob Heller
get started
Enjoy this post?

Leave a like and comment for Rob

1
6
Swift Tips & Tricks: Using Functions as Parameters in Swift
How to Create Delegates in Swift
How PHP 7 Handles Exceptions