Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Tuomo Kankaanpää
13,574 PointsWhat is the best way to make POST/GET requests with Objective-C?
Ahoy fellow treehouse members!
I am working on an iOS app that needs to make several GET and POST requests to different URLs over the web. I also need to be able to add custom headers to the requests. I am getting JSON data back from the URLs.
I am looking for someone to point me into the right direction on what would be the best solution in accomplishing this kind of behaviour. For example in the Ribbit project we are using Parse.framework that seems to be doing all the hard work and same time keeps the code easily readable. Should I try to create this kind of framework on my own? How? Or is there some kind of handy networking libraries that have been proven awesome and suit this kind of purpose? Or something else?
I am targeting iOS7 and as mentioned in the title the language is Objective-C. Hopefully my explanation wasn't too confusing! ;) Thanks!
-Tuomo
1 Answer
Adham Gad
9,899 PointsFor GET Requests
NSURL *url = [[NSURL alloc]initWithString:@"http://example.com/ "];
//type your URL u can use initWithFormat for placeholders
NSURLSession *session = [NSURLSession sharedSession]; //use NSURLSession class
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
//You then can use NSURLSessionDownloadTask or NSURLSessionUploadTask
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
//note that your requested data are stored on the disk automatic
// if u need to retrieve your data use the location parameter not the response parameter
//as it stores the location of ur retrieved data that was saved on the disk
//works asynchronously i think
}];
[task resume]; // to start the download task
For POST Requests same thing but use NSMutableURLRequest instead of NSURLRequest and then set your Method to POST
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:url];
request.HTTPMethod = @"POST";
Check Sam's videos they were good https://teamtreehouse.com/library/build-a-photo-browser-iphone-app/downloading-data-with-nsurlsession/what-is-asynchronous-networking