-
-
Save Mabdelwanis/1609955819a942c1ae299aa74f83be25 to your computer and use it in GitHub Desktop.
POST request to a URL using Objective-C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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