Which is the best method to fetch data from JSON url? - json

I have a application in which when we login a new view controller will be loaded which is a table view and data need to be fetched from server by Json call.Which is the best method to use in this situation.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://YourURL.com/FakeURL/PARAMETERS"]];
[request setHTTPMethod:#"GET"];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
or
-(void)update{
NSString *urlAsString = [NSString stringWithFormat:#"http://YourURL.com/FakeURL/PARAMETERS"];
NSURL *url = [[NSURL alloc] initWithString:urlAsString];
self.responseData = [NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:
url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse");
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"didFailWithError");
NSString *errorDisplay = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
NSLog(#"%#",errorDisplay);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.responseData length]);
// convert to JSON
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
}
Or i should use Asynchronous Method
-(void)updateCheckList{
self.checkListresponseData = [NSMutableData data] ;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost:8080/outing-service-web/checkList/all"]];//asynchronous call
checkListConn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse");
[self.checkListresponseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.checkListresponseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"didFailWithError");
NSString *errorDisplay = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
NSLog(#"%#",errorDisplay);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Cannot connect to server" delegate:nil cancelButtonTitle:nil otherButtonTitles: #"Retry",#"Close",nil];
[alertView show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (connection == checkListConn) {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.checkListresponseData length]);
// convert to JSON
NSError *myError = nil;
NSArray *res = [NSJSONSerialization JSONObjectWithData:self.checkListresponseData options:NSJSONReadingMutableLeaves error:&myError];
}
}

If you do it asynchronously, then the process will be done in the background.
In short, synchronous requests block the execution of code which creates "freezing" on the screen and an unresponsive user experience.
Check the following URL, it might get you more clear idea.
Synchronous and Asynchronous Requests

Related

AFNetworking, NSURLSession and json Response (Ronak Sankhala)

I am trying to get json response from a web-service api. I want to extract product data from the json. I also want to implement this using AFNetworking and i also trying to get response using NSURLSession and its completely working.
viewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *tblTableView;
- (IBAction)btnClickedPostData:(id)sender;
#end
viewController.m
#import "ViewController.h"
#import "AFNetworking.h"
#import "ResponseTableViewCell.h"
#interface ViewController ()
{
NSMutableDictionary *dictArray;
NSMutableArray *dataArray;
}
#end
#implementation ViewController
static NSString *CellIdentifier = #"cell";
- (void)viewDidLoad {
[super viewDidLoad];
[self.tblTableView registerNib:[UINib nibWithNibName:#"ResponseTableViewCell" bundle:nil] forCellReuseIdentifier:#"ResponseTableViewCell"];
[self connectionString];
}
-(void)connectionString
{
//NSURL *URL = [NSURL URLWithString:#"Your URL"];
NSURLSession *session = [NSURLSession sharedSession]; // its working
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:#"YOUR URL"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", jsonResponse);
dataArray = [jsonResponse objectForKey:#"objEventcategoryList"];
self.tblTableView.dataSource = self;
self.tblTableView.delegate = self;
[self.tblTableView reloadData];
NSLog(#"JSON: %#", dataArray);
}];
[dataTask resume];
// AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // its working
// [manager GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
//
// NSMutableDictionary *jsonResponse = (NSMutableDictionary *)responseObject;
// dataArray = [jsonResponse objectForKey:#"objEventcategoryList"];
//
// self.tblTableView.dataSource = self;
// self.tblTableView.delegate = self;
//
// [self.tblTableView reloadData];
//
// NSLog(#"TableView: %#", _tblTableView);
//
//
// NSLog(#"JSON: %#", dataArray);
// } failure:^(NSURLSessionTask *operation, NSError *error) {
// NSLog(#"Error: %#", error);
// }];
}
#pragma marrk
#pragma marrk - TableView DataSource and Deleget
#pragma marrk
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dataArray count];// its not working
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ResponseTableViewCell *cell = (ResponseTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"ResponseTableViewCell"];
dictArray = [dataArray objectAtIndex:indexPath.row];
//cell.lblCatID.text = [dictArray objrct:#""];
cell.lblCatID.text = [NSString stringWithFormat:#"%#", [dictArray valueForKey:#"EventCategoryId"]];
cell.lblEventName.text = [NSString stringWithFormat:#"%#", [dictArray valueForKey:#"EventCategoryName"]];
cell.lblCreateDate.text = [NSString stringWithFormat:#"%#", [dictArray valueForKey:#"CreatedDate"]];
cell.layoutMargins = UIEdgeInsetsZero;
return cell;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([tableView respondsToSelector:#selector(setSeparatorInset:)])
{
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tableView respondsToSelector:#selector(setLayoutMargins:)])
{
[tableView setLayoutMargins:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:#selector(setLayoutMargins:)])
{
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 144.0;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnClickedPostData:(id)sender {
NSString *tokenString = #"65d188d3f0ab52487001c331584ac819";
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
[defaultConfigObject setHTTPAdditionalHeaders:#{ #"token" : tokenString}];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:#"YOUR URL"];
NSString *paramString = #"lang=en&title=&start=&end=";
NSData *httpBody = [paramString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:60.0];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[httpBody length]];
[urlRequest addValue: #"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setHTTPMethod:#"POST"];
//[urlRequest setAllHTTPHeaderFields:paramString];
[urlRequest setAllHTTPHeaderFields:#{ #"token" : tokenString}];
[urlRequest setHTTPBody:httpBody];
//[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSError *parseError = nil;
NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;
if (!error && respHttp.statusCode == 200) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSMutableArray *arrArray = [responseDictionary objectForKey:#"newslist"];
NSString *title = [NSString stringWithFormat:#"%#", [arrArray valueForKey:#"title"]];
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:#"Details" message:title delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:#"Cancel", nil];
[alert show];
NSLog(#"%#", arrArray);
}else{
NSLog(#"%#", error);
}
}];
[dataTask resume];
}
#end
//CustomeTableviewCell With XIB
**ResponseTableViewCell.h**
#import <UIKit/UIKit.h>
#interface ResponseTableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *lblCatID;
#property (weak, nonatomic) IBOutlet UILabel *lblEventName;
#property (weak, nonatomic) IBOutlet UILabel *lblCreateDate;
#end
**ResponseTableViewCell.m**
#import "ResponseTableViewCell.h"
#implementation ResponseTableViewCell
#synthesize lblCatID,lblEventName,lblCreateDate;
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
// and also download and check JSON demo : https://drive.google.com/open?id=0B0rS2ZVDMVRiSmJJb1BuQklJSzA[Click to show JSON demo Hear][1]
//add custom table view cell with custom table cell and add label to display information. i used pod to setup AFNetworking.
and also download and check JSON demo : https://drive.google.com/open?id=0B0rS2ZVDMVRiSmJJb1BuQklJSzAClick to show JSON demo Hear
Can anyone suggest a way to do this.me how the things will be done.
You Can use also use sqlite for the data.

Passing param in URL to get json back in IOS

Sorry i am really beginner in IPhone development,i am pulling json data from URL and its pulling and loading data perfectly in UITableView, below is code
- (void)fetchFeed
{
NSString *requestString = #"http://bookapi.bignerdranch.com/courses.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
self.session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask =
[self.session dataTaskWithRequest:req
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
self.courses = jsonObject[#"courses"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}];
[dataTask resume];
}
Now i want to add filter by instructors, Can any one tell me how i can do that.
Thanks
GET
GET request is just a matter of appending query strings to the API url, for example:
NSString *format = [NSString stringWithFormat:#"http://www.yourapiurl.com?id=%#","123";
NSURL *url = [NSURL URLWithString:format];
NSLog(#"%#",url);
//Creating the data object that will hold the content of the URL
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
POST
-(NSData *)post:(NSString *)postParams{
//Build the Request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.yourapiurl.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postParams length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postParams dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
return returnData;
}
usage:
NSString *postString = [NSString stringWithFormat:#"prop1=%#&prop2=%#&prop3=%#",
"value1","value2","value3"];
NSData *JsonData = [self post :postString];
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:JsonData options:NSJSONReadingMutableContainers error:nil];
//then parse the JSON

Objective-C Authentication

I am currently writing an iPhone application that will push a username and password to a website to retrieve the HTML source code of the page which loads. I include login information in NSString *post.
When I NSLog the _responseData instance variable in the connectionDidFinishLoading method, the console prints a long series of eight digit hexadecimal numbers which I assume are some type of address or encrypted HTML (3c21444f 43545950 45206874 6d6c2050 55424c49 4320222d 2f2f5733...).
What should I do to convert/decrypt the addresses into HTML code or otherwise retrieve the HTML code of the webpage which loads?
My ViewController conforms to the NSURLConnectionDelegate protocol and includes the following code:
#interface ViewController : UIViewController<NSURLConnectionDelegate>
{
NSMutableData *_responseData;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
NSLog(#"Received response");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
NSLog(#"Received data");
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
//NSString *html=[NSString stringWithContentsOfURL:[NSURL URLWithString:#"https://grades.bsd405.org/Pinnacle/Gradebook/InternetViewer/GradeSummary.aspx?&EnrollmentId=770595&TermId=127463&ReportType=0&StudentId=114040"] encoding:NSASCIIStringEncoding error:nil];
NSLog(#"Finished loading");
//PRINT HTML:
NSLog(#"Data: %#",_responseData);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
NSLog(#"Failed to load");
}
- (IBAction)goPressed:(UIButton *)sender {
NSString *post = #"__LASTFOCUS&__EVENTTARGET&__EVENTARGUMENT&__VIEWSTATE=/wEPDwUJNTkxNzI3MDIzD2QWAmYPZBYCA
gMPZBYGAgEPZBYCAgkPZBYCAgEPZBYIAgMPFgIeB1Zpc2libGVoZAIFDxYCHwBoZAIHDxYCHwBoZAIJDxYCHgVzdH
lsZQUjdmVydGljYWwtYWxpZ246bWlkZGxlO2Rpc3BsYXk6bm9uZTtkAgMPDxYCHwBoZGQCBQ9kFghmD2QWAgINDxY
CHgVjbGFzcwUQc2luZ2xlU2Nob29sTGlzdBYCAgEPZBYCAgEPEGQPFgFmFgEQBQ5EZWZhdWx0IERvbWFpbgUIUGlu
bmFjbGVnZGQCAg9kFgICEw9kFgICAQ9kFgICAQ8QZGQWAGQCBw8PFgIeBFRleHQFIFBpbm5hY2xlIEdyYWRlIDIwM
TIgV2ludGVyIEJyZWFrZGQCCA8PFgIfAwU3Q29weXJpZ2h0IChjKSAyMDEzIEdsb2JhbFNjaG9sYXIuICBBbGwgcm
lnaHRzIHJlc2VydmVkLmRkZP/l6irI9peZfyqpKjk3fwLuEbos&__EVENTVALIDATION=/wEWBgKjnbqUCQLnksmg
AQKTpbWbDgLB5+KIBAL4xb20BAK20ZqiCel6sQLBsF1W3XHOxpgq+tJj+Rx2&ctl00$ContentPlaceHolder$Use
rname=TESTUSERNAME&ctl00$ContentPlaceHolder$Password=TESTPASSWORD&ctl00$ContentPlaceHolde
r$lstDomains=Pinnacle&ctl00$ContentPlaceHolder$LogonButton=Sign
in&PageUniqueId=2dacba26-
bb0d-412f-b06a-e02caf039c4b";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://grades.bsd405.org/Pinnacle/Gradebook/Logon.aspx?ReturnUrl=%2fPinnacle%2fGradebook%2fDefault.aspx"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:request delegate:self];
}
The NSLog of your NSData displays the object's description, which a hexadecimal string of the underlying binary data:
3c21444f 43545950 45206874 6d6c2050 55424c49 4320222d 2f2f5733 ...
Translates to a string of
<!DOCTYPE html PUBLIC "-//W3 ...
To get the NSString from the NSData, you do:
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

Cocoa HTTP POST Request [Mac OS X]

I spent a lot of time for research on POST Requests using Cocoa.
I found some code that looked good. I changed it like it fits my needs. But the code didn't work and I can't find the bug because I'm pretty new to cocoa.
Here is my code.
- (IBAction)sendForm:(id)sender
{
NSLog(#"web request started");
NSString *post = [NSString stringWithFormat:#"firstName=%#&lastName=%#&eMail=%#&message=%#", firstName.stringValue, lastName.stringValue, eMail.stringValue, message.stringValue];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"myDomain/form.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
webData = [[NSMutableData data] retain];
NSLog(#"connection initiated");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
NSLog(#"connection received data");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"connection received response");
NSHTTPURLResponse *ne = (NSHTTPURLResponse *)response;
if([ne statusCode] == 200)
{
NSLog(#"connection state is 200 - all okay");
NSString *html = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
[[webView mainFrame] loadHTMLString:html baseURL:[NSURL URLWithString:#"myDomain"]];
}
}
But the only two NSLog messages I receive are "web request started" and "connection initiated".
So I think - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data and - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)responseare not called.
Can anybody help me with this issue?
Thanks for help, Julian
You almost did it correctly!
I can see the post is a year old but in the hope that it may help others and for my own reference, I am posting this here.
Apple's documentation for connection:didReceiveResponse: says :-
Sent when the connection has received sufficient data to construct the
URL response for its request.
As with most Apple documentation this too is confusing and maybe misleading. Usually when we have "sufficient data to construct the URL response" means we have the complete response which further means that we have response body too; which is universally considered part of the response.
However in this case the NSHTTPURLResponse object does not have a body. So my guess is, what Apple means is - connection:didReceiveResponse: is invoked when we have received the response header which has "sufficient" data to let us known everything about the response, except the actual data (body).
In fact many times you will notice that connection:didReceiveData: gets called after connection:didReceiveResponse: is invoked.
So, we can modify your code as below :-
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSLog(#"web request started");
NSString *post = [NSString stringWithFormat:#"firstName=%#&lastName=%#&eMail=%#&message=%#", firstName.stringValue, lastName.stringValue, eMail.stringValue, message.stringValue];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%ld", (unsigned long)[postData length]];
NSLog(#"Post data: %#", post);
NSMutableURLRequest *request = [NSMutableURLRequest new];
[request setURL:[NSURL URLWithString:#"https://example.com/form.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection) {
webData = [NSMutableData data];
NSLog(#"connection initiated");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
NSLog(#"connection received data");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"connection received response");
NSHTTPURLResponse *ne = (NSHTTPURLResponse *)response;
if([ne statusCode] == 200) {
NSLog(#"connection state is 200 - all okay");
} else {
NSLog(#"connection state is NOT 200");
}
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Conn Err: %#", [error localizedDescription]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Conn finished loading");
NSString *html = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"OUTPUT:: %#", html);
}
Have you tried to implement the error delegate method?
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// do something with error
}
It can happen that you don't have an internet connection, or something else is wrong before NSURLConnection is able to establish a connection. In this case you will not receive a http response or any other data. The error will provide more information.
[edit]
I just noticed the URL in the example code doesn't contain a host name. If this is the exact code you are using make sure you send the request to a correct URL.
// Replace
[NSURL URLWithString:#"myDomain/form.php"]
// with a correct url like
[NSURL URLWithString:#"http://mydomain.com/form.php"];
An error delegate method will actually provide you with an error that complains about a wrong URL.

json ios5 nothing at the screen

i have just install the xcode 4.2.1 with ios5 and i try to use json.
this my code
-(void)start
{
responseData = [[NSMutableData data]retain];
membreArray = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http:******.php"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"error %#",error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
jsonArray = [responseString JSONValue];
NSLog(#"array %#",jsonArray);
}
in my NSLog(#"array %#",jsonArray); i can see all records,everything is ok. But in my tableview nothing at the screen.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [jsonArray count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell.
NSDictionary *dico = [self.jsonArray objectAtIndex:indexPath.row];
cell.textLabel.text = [dico objectForKey:#"name"];
return cell;
}
this code work on xcode 3 but not in xcode 4.
somes helps please.
After you finish loading the data, you need to tell your tableview to reload. I'm not seeing that in your code. Try something like this:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
jsonArray = [responseString JSONValue];
NSLog(#"array %#",jsonArray);
/* This tells your tableView to reload */
[tableView reloadData];
}
Also, make sure your TableView is connected in the designer via an IBOutlet. Otherwise your reloadData command will fall on deaf ears.