Skip to content

Instantly share code, notes, and snippets.

@Mabdelwanis
Forked from wptechprodigy/sendPOSTRequestWithUR.m
Created December 17, 2023 22:58
Show Gist options
  • Save Mabdelwanis/1609955819a942c1ae299aa74f83be25 to your computer and use it in GitHub Desktop.
Save Mabdelwanis/1609955819a942c1ae299aa74f83be25 to your computer and use it in GitHub Desktop.
POST request to a URL using Objective-C
- (void)sendPOSTRequestWithURL:(NSURL *)url parameters:(NSDictionary *)parameters completionHandler:(void (^)(NSData *, NSURLResponse *, NSError *))completionHandler {
// Create a mutable URL request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Set the request method to POST
[request setHTTPMethod:@"POST"];
// Set the request body with the parameters
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
[request setHTTPBody:postData];
// Create a session configuration
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// Create a session with the configuration
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
// Create a data task with the request
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:completionHandler];
// Start the data task
[dataTask resume];
}
NSURL *url = [NSURL URLWithString:@"https://example.com/api"];
NSDictionary *parameters = @{@"key1": @"value1", @"key2": @"value2"};
[self sendPOSTRequestWithURL:url parameters:parameters completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
// Handle the response data
}
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment