I'm approaching iOS development and I'd like to have one of my first applications to perform a HTTP POST request.
As far as I can understand, I should manage the connection which handles the request via a NSURLConnection
object, which forces me to have a delegate object, which in turn will handle data events.
Could someone please clarify the task with a practical example?
I should contact an https endpoint sending authentication data (username and password) and getting back a plain text response.
NOTE: Pure Swift 3 (Xcode 8) example: Please try out the following sample code. It is the simple example of
dataTask
function ofURLSession
.EDIT: ASIHTTPRequest has been abandoned by the developer. It's still really good IMO, but you should probably look elsewhere now.
I'd highly recommend using the ASIHTTPRequest library if you are handling HTTPS. Even without https it provides a really nice wrapper for stuff like this and whilst it's not hard to do yourself over plain http, I just think the library is nice and a great way to get started.
The HTTPS complications are far from trivial in various scenarios, and if you want to be robust in handling all the variations, you'll find the ASI library a real help.
Here is how POST HTTP request works for iOS 8+ using NSURLSession:
Hope this will satisfy your following requirement.
I thought I would update this post a bit and say that alot of the iOS community has moved over to AFNetworking after
ASIHTTPRequest
was abandoned. I highly recommend it. It's a great wrapper aroundNSURLConnection
and allows for asynchronous calls, and basically anything you might need.You can use NSURLConnection as follows:
Set your
NSURLRequest
: UserequestWithURL:(NSURL *)theURL
to initialise the request.If you need to specify a POST request and/or HTTP headers, use
NSMutableURLRequest
with(void)setHTTPMethod:(NSString *)method
(void)setHTTPBody:(NSData *)data
(void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field
Send your request in 2 ways using
NSURLConnection
:Synchronously:
(NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
This returns a
NSData
variable that you can process.IMPORTANT: Remember to kick off the synchronous request in a separate thread to avoid blocking the UI.
Asynchronously:
(void)start
Don't forget to set your NSURLConnection's delegate to handle the connection as follows:
Here is an updated answer for iOS7+. It uses NSURLSession, the new hotness. Disclaimer, this is untested and was written in a text field:
Or better yet, use AFNetworking 2.0+. Usually I would subclass AFHTTPSessionManager, but I'm putting this all in one method to have a concise example.
If you are using the JSON response serializer, the responseObject will be object from the JSON response (often NSDictionary or NSArray).