i have another problem this time, i'm fetching json codes that will be used to populate the tableview i have in my xib so, to start with my .h file
#interface FirstViewController : UIViewController<UITableViewDelegate, UITableViewDataSource, ASIHTTPRequestDelegate> {
NSMutableArray *resultArray;
IBOutlet UITableView *thetableView;
NSMutableData *responseData;
}
#property (nonatomic,retain) NSArray *arrayTypes;
#property (nonatomic,retain) NSMutableArray *resultArray;
#property (nonatomic,retain) IBOutlet UITableView *thetableView;
in my .m file i implemented this
- (void) viewDidLoad{
responseData = [[NSMutableData data]retain];
NSURL *url = [NSURL URLWithString:#"http://localhost/fetch.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[super viewDidLoad];
[self.thetableView reloadData];
}
in the connectiondidfinishloading:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSLog(#"%#", responseString);
NSDictionary *dictionary = [responseString JSONValue];
NSMutableArray *response = [dictionary valueForKey:#"itemn"];
resultArray = [[NSArray alloc] initWithArray:response];
}
and now the problem, the tableview has implemented both the numberofrowsinsection and didselectrowatindextpath methods but the latter is never called as the size of the array is 0 and even reloading, it doesn't work am i missing something or is there a similar tutorial to follow? sorry for the length just hoping the infos will be useful
you should reload tableview once you have the complete data..see the updated code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSLog(#"%#", responseString);
NSDictionary *dictionary = [responseString JSONValue];
NSMutableArray *response = [dictionary valueForKey:#"itemn"];
resultArray = [[NSArray alloc] initWithArray:response];
//Reload your table with data..
[self.thetableView reloadData];
}
Related
I am trying to get the values from a few UITextFields I have added to my storyboard and send them as a JSON string to an API. I can hard code the values for the JSON string and everything works fine. Now I want to retrieve the values from the text fields and insert them in place of the hard coded values. The problem is that when I log the values to the console they are showing up as blank. I am not sure that I have the code correct to get the values from the ViewController to the method that sends the data. I followed several tutorials on how to get the data from the ViewController UITextFields. I connected the text fields to the properties in the ViewController.h file. I am hoping someone can help me figure out what I did wrong, hopefully I provided enough information.
I think the problem may be how I am trying to get the values from these lines of code in the timeMethods.m file:
ViewController *controller = [[ViewController alloc]initWithNibName:#"ViewController" bundle:nil];
NSString *name = controller.name.text;
NSString *type = controller.type.text;
NSString *date = controller.date.text;
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (nonatomic, retain) IBOutlet UITextField *name;
#property (nonatomic, retain) IBOutlet UITextField *type;
#property (nonatomic, retain) IBOutlet UITextField *date;
#end
ViewController.m
#import "ViewController.h"
#import "timeMethods.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize name;
#synthesize type;
#synthesize date;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)sendRequest:(id)sender {
[[timeMethods alloc] sendRequest];
}
- (IBAction)getRequest:(id)sender {
[[timeMethods alloc] getRequest];
}
#end
timeMethods.m
#import "timeMethods.h"
#implementation timeMethods
- (void)sendRequest {
ViewController *controller = [[ViewController alloc]initWithNibName:#"ViewController" bundle:nil];
NSString *name = controller.name.text;
NSString *type = controller.type.text;
NSString *date = controller.date.text;
NSURL *url = [NSURL URLWithString:#"http://throttle.com/my-rest-api/api/robots"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
name, #"name",
type, #"type",
date, #"year",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSString *strData = [[NSString alloc]initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"%#", strData);
}
- (void)getRequest {
NSString *serverAddress = #"http://throttle.com/my-rest-api/api/robots";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[request setHTTPMethod:#"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSString *strData = [[NSString alloc]initWithData:response1 encoding:NSUTF8StringEncoding];
NSLog(#"%#",strData);
}
#end
timeMethods.h
#import <Foundation/Foundation.h>
#interface timeMethods : NSObject
- (void)sendRequest;
- (void)getRequest;
#end
The trouble is that we've just allocated a brand new VC and asked for its UITextField's values here:
ViewController *controller = [[ViewController alloc]initWithNibName:#"ViewController" bundle:nil];
// controller.name is a brand new text field, created in the previous line
NSString *name = controller.name.text; // guaranteed to be #""
Of course this will be an empty text field. It was created in the previous line. Instead, get those values as params to your request from the view controller the user is using...
- (IBAction)sendRequest:(id)sender {
NSString *name = self.name.text;
NSString *type = self.type.text;
NSString *date = self.date.text;
[[timeMethods alloc] sendRequestWithName:name type:type date:date];
}
Naturally, add those parameters to the sendRequest method and remove the local vars.
I have hobbled together one of my first objects. The goal of the object is to send a text message, which is does. However I'm calling it from the 2nd UIViewController within ViewDidLoad, and its still hanging within the Segue transition. So I know I need to get it asynchronously, but reading some other threads they implied that the proper way to go around it is to make it an "AppDelegate Object", so I would assume I would need to call the object from the AppDelegate, but I'm not really sure about how to go about that as I have not really worked with that in some tutorials I'm doing, and on top of that, is that the correct way to go about using my object?
initializing the object from my view controller
Twilio *twilio = [[Twilio alloc] init];
[twilio sendMessage: self.phoneNumber: [self getRandomNumberBetween:1000 to:9999]];
Header file
#import <Foundation/Foundation.h>
#interface Twilio : NSObject
#property (strong, nonatomic) NSString *TwilioSID;
#property (strong, nonatomic) NSString *TwilioSecret;
#property (strong, nonatomic) NSString *FromNumber;
#property (strong, nonatomic) NSString *ToNumber;
#property (strong, nonatomic) NSString *Message;
-(id)init;
-(id)sendMessage:(NSString *)phoneNumber :(NSString *)message;
#end
Implementation file
#import "Twilio.h"
#implementation Twilio
-(id)init {
self = [super init];
if(self) {
// Twilio Common constants
self.TwilioSID = #"A....3";
self.TwilioSecret = #"e...8";
self.FromNumber = #"5...2";
self.ToNumber = nil;
self.Message = nil;
}
return self;
}
-(id)sendMessage:(NSString *)phoneNumber :(NSString *)message
{
NSLog(#"Sending request.");
self.ToNumber = phoneNumber;
self.Message = message;
// Build request
NSString *urlString = [NSString stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages", self.TwilioSID, self.TwilioSecret, self.TwilioSID];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
// Set up the body
NSString *bodyString = [NSString stringWithFormat:#"From=%#&To=%#&Body=%#", self.FromNumber, self.ToNumber, self.Message];
NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
NSError *error;
NSURLResponse *response;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// Handle the received data
if (error) {
NSLog(#"Error: %#", error);
} else {
NSString *receivedString = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Request sent. %#", receivedString);
}
return self.Message;
}
#end
Updated
With recommendation below I changed my object implementation like so:
//NSError *error;
//NSURLResponse *response;
//NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[NSURLConnection sendAsynchronousRequest:request queue:self.queue completionHandler:^(NSURLResponse *response, NSData *data, NSError
*error) {
// Handle the received data
if (error) {
NSLog(#"Error: %#", error);
} else {
NSString *receivedString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Request sent. %#", receivedString);
}
NSLog(#"%#",response);
}];
Use method sendAsynchronousRequest:queue:completionHandler:
See it : https://stackoverflow.com/a/9270711/2828120
I have one main entity class with name "Store" like :
Store.h :-
#import <Foundation/Foundation.h>
#import "SignIn.h"
#interface Store : NSObject
#property (nonatomic, retain) NSString *storeId;
#property (nonatomic, retain) NSString *storeProfileId;
#property (nonatomic, retain) NSString *storeName;
#property (nonatomic, retain) NSString *storeRegion;
#property (nonatomic, retain) SignIn *signIn;
#end
Store.m :-
#import "Store.h"
#implementation Store
#synthesize storeId, storeProfileId, storeName, storeRegion, signIn;
- (id) initWithCoder: (NSCoder *)coder
{
self = [[Store alloc] init];
if (self != nil)
{
self.storeId = [coder decodeObjectForKey:#"storeId"];
self.storeProfileId = [coder decodeObjectForKey:#"storeProfileId"];
self.storeName = [coder decodeObjectForKey:#"storeName"];
self.storeRegion = [coder decodeObjectForKey:#"storeRegion"];
self.signIn = [coder decodeObjectForKey:#"signIn"];
}
return self;
}
- (void)encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject:storeId forKey:#"storeId"];
[coder encodeObject:storeProfileId forKey:#"storeProfileId"];
[coder encodeObject:storeName forKey:#"storeName"];
[coder encodeObject:storeRegion forKey:#"storeRegion"];
[coder encodeObject:signIn forKey:#"signIn"];
}
#end
Here in Store class, i am taking one more class name "Sign In", that include some other attributes.
SignIn.h :-
#import <Foundation/Foundation.h>
#interface SignIn : NSObject
#property (nonatomic, retain) NSString *inTime;
#property (nonatomic, retain) NSString *outTime;
#property (nonatomic, retain) NSString *isStatus;
#end
SignIn.m :-
#import "SignIn.h"
#implementation SignIn
#synthesize inTime, outTime, isStatus;
- (id) initWithCoder: (NSCoder *)coder
{
self = [[SignIn alloc] init];
if (self != nil)
{
self.inTime = [coder decodeObjectForKey:#"inTime"];
self.outTime = [coder decodeObjectForKey:#"outTime"];
self.isStatus = [coder decodeObjectForKey:#"isStatus"];
}
return self;
}
- (void)encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject:inTime forKey:#"inTime"];
[coder encodeObject:outTime forKey:#"outTime"];
[coder encodeObject:isStatus forKey:#"isStatus"];
}
#end
Now i need to post this Store object on server. So I am creating dictionary using below code :
NSMutableArray *storeJSONArray=[NSMutableArray array];
for (Store *store in array1) {
NSMutableDictionary *storeJSON=[NSMutableDictionary dictionary];
[storeJSON setValue:store.storeId forKey:#"storeId"];
[storeJSON setValue:store.storeProfileId forKey:#"storeProfileId"];
[storeJSON setValue:store.storeName forKey:#"storeName"];
[storeJSON setValue:store.storeRegion forKey:#"storeRegion"];
//Sign In
[storeJSON setValue:store.signIn.inTime forKey:#"inTime"];
[storeJSON setValue:store.signIn.outTime forKey:#"outTime"];
[storeJSON setValue:store.signIn.isStatus forKey:#"isStatus"];
[storeJSONArray addObject:storeJSON];
}
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:storeJSONArray forKey:#"StoreRequest"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString =#"http://...................php";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
But i am not getting correct JSON, can you please check my code and let me know where is my mistake. Thanks in Advance.
If you are working on iOS 5+, then you can use NSJSONSerialization.
NSData *data= [NSJSONSerialization dataWithJSONObject:storeJSONArray
options:NSJSONWritingPrettyPrinted
error:nil];
if (data)
{
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON : %#",json );
}
You should serialize your NSMutableDictionary to JSON.
You can do this by using NSJSONSerialization:
NSError *error;
NSData *myData = [NSJSONSerialization dataWithJSONObject:storeJSON options:0 error:&error];
NSString *myJSON = [[NSString alloc] initWithBytes:[myData bytes]];
This should give you your JSON.
But i am not getting correct JSON, can you please check my code and let me know where is my mistake.
The problem is that you're not creating a JSON representation of the object anywhere; you're only creating a dictionary. Dictionaries can be converted to JSON (provided that they only contain certain types of data), but they're not JSON natively -- they're Objective-C objects. You probably want to add a call like:
NSError *error = nil;
NSData *json = [NSJSONSerialization dataWithJSONObject:dictionnary options:0 error:&error];
You've shown us the NSCoding methods in your two classes, but you should understand that NSJSONSerialization doesn't rely on NSCoding, so none of that code is going to come into play.
Update: After modifying your example to include NSJSONSerialization, you say you're getting JSON that looks like this:
{"StoreRequest":[{"signOutStatus":false,"greetingStatus":false,"isBackFromVisit":false,"digitalMerchandisingStatus":false,"feedbackStatus":false,"storeRegion":"Bishan Junction 8","isSubmit":false,"storeName":"Best Denki","storeId":"SG-2","planVisitStatus":false,"storeProfileId":5,"merchandisingStatus":false}]}
That appears to be correct, given the values that you've added to dictionnary. But you say that what you want is:
{ "Checklist": [ { "vm_code": "SGVM0001", "store_id": "SG-12", "store_name": "Best Denki", "store_address": "Ngee Ann City", "visit_date": { "date": "2013-12-04 00:00:00", "timezone_type": 3, "timezone": "Asia/Calcutta" } "sign_in": { "date": "2013-12-05 11:03:00", "timezone_type": 3, "timezone": "Asia/Calcutta" }]
That doesn't at all match the object that you're passing to NSJSONSerialization. So, the problem here is that you're supplying incorrect data to NSJSONSerialization.
Try with
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:kNilOptions // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
I'm starting NSURLConnection, parsing XML, initialize array from this XML, and show it in the tableView. In connectionDidFinishLoading I'm trying [self.tableView reloadData, but it doesn't work. This is my code:
my .h file:
#interface catalogViewController : UITableViewController //
#property (nonatomic, strong) NSMutableData *receivedData;
#property (nonatomic,retain) NSArray * titleArr;
#property (nonatomic,retain) NSArray * contentArr;
#property (nonatomic,retain) NSArray * ImageURLArr;
#property (nonatomic,retain) NSArray * dateArr;
#property (nonatomic,retain) NSArray * priceArr;
#property (nonatomic,retain) NSDictionary * xmlDictionary;
#property (nonatomic,retain) NSArray * IDArr;
#property (nonatomic) BOOL * didDataLoaded;
#property (strong, nonatomic) IBOutlet UITableView *myTableView;
#end
My .m file:
#import "catalogViewController.h"
#import "XMLReader.h"
#interface catalogViewController ()
#end
#implementation catalogViewController
- (id)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) { } return self;
}
//-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-CONNECTIONS METHOD START-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
[_receivedData release];
NSString *errorString = [[NSString alloc] initWithFormat:#"Connection failed! Error - %# %# %#", [error localizedDescription], [error description], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]; NSLog(#"%#",errorString);
[errorString release];
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-GET FULL DATA HERE-=-=-=-=-=-=-=-=--=-=-=-=-=-=-
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *dataString = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
NSString *testXMLString = [NSString stringWithContentsOfURL:myURL usedEncoding:nil error:nil];
// -=-=-=-=-=-=-=-=-=-=Parse the XML into a dictionary-=-=-=-=-=-=-=-=-=-=
NSError *parseError = nil;
_xmlDictionary = [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART END-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
_titleArr =[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"name"] valueForKey:#"text"];
_IDArr =[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"id"] valueForKey:#"text"];
_priceArr=[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"price"] valueForKey:#"text"];
_ImageURLArr=[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"img"] valueForKey:#"text"];
[connection release];
[_receivedData release];
[dataString release];
_didDataLoaded=TRUE;
[_myTableView reloadData]; // IBOutlet property
[self.tableView reloadData]; //default
}
//-=-=-=-=-=-=-=-=-=-=-Connection methods END-=-=-=-=-=-=-=-=-=-
- (void)viewDidLoad {
[super viewDidLoad];
_didDataLoaded=FALSE;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//-=-==-=-=-=-=-=-=-=-=-=-=--=-=START Shit with connection-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=
NSString* params = #"request_params";
NSURL* url = [NSURL URLWithString:#"my URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"POST";
request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSLog(#"Connecting...");
_receivedData = [[NSMutableData data] retain];
} else {
NSLog(#"Connecting error");
}
}
//-=-==-=-=--=-==-=-=-=-=-=--=-==---=-=--==-=-=-=-=-TableView methods-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=--=-=-=-=-=-=-=
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (_didDataLoaded == FALSE) {
return 1;
}
else return self.titleArr.count;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { return 1; }
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"creatures"];
UIImage *creatureImage = nil;
if (_didDataLoaded == FALSE) {
cell.textLabel.text=#"Downloading...";
cell.detailTextLabel.text= #"downloading...";
} else {
cell.textLabel.text = [self.titleArr objectAtIndex:indexPath.row];
cell.detailTextLabel.text= _IDArr[indexPath.row];
NSString *img = self.ImageURLArr[indexPath.row];
creatureImage =[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:img]]]; cell.imageView.image = creatureImage;
}
return cell;
}
#end
XML downloading - OK, parsing - OK, initialising arrays - OK. But when I start project I have exception on the line NSLog(#"%#", self.titleArr objectAtIndex:indexPath.row]; - says: "Thread 1: EXC_BAD_ACCESS (code 1)
How can I understand it's means that it's trying initialize array when it's not prepare. My problem is i can't delay tableView methods or what? How can i fix it? I'm trying fix itfor some days...
Your titleArr is deallocated from memory and then you are requesting object of it so it is giving you a crash. So allocate memory to array by this way.
_titleArr = [[NSArray alloc] initWithArray:[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"name"] valueForKey:#"text"]];
Eventhough it's not recommended way but the following can provide a solution to you
self.tableView.delegate = nil;
self.tableView.datasource = nil;
and when safely your array was populated with the xml data set back to
self.tableView.delegate = self;
self.tableView.datasource = self;
I'm experiencing a problem with my code but I'm not sure why it's doing this. It's just giving me an error saying JSON Error. The UITableView never gets filled with anything. I'm not very experienced with iOS, so any help is appreciated.
//
// ViewController.m
// Westmount Procrastinator
//
// Created by Saleem on 10/25/13.
// Copyright (c) 2013 Saleem Al-Zanoon. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UIWebView *webView;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *fullURL = #"********";
NSURL *url2 = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url2];
[_webView loadRequest:requestObj];
self.title = #"News";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"****************"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self]; // NSString * urlString = [NSString stringWithFormat:#"http://salespharma.net/westmount/get_all_products.php"];
// NSURL * url = [NSURL URLWithString:urlString];
// NSData * data = [NSData dataWithContentsOfURL:url];
// NSError * error;
// NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// NSLog(#"%#",json);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
//news = [responseDict objectAtIndex:0];
// [mainTableView reloadData];
if ([responseDict isKindOfClass:[NSArray class]]) {
news = responseDict;
[mainTableView reloadData];
} else {
// Looks like here is some part of the problem but I don't know why.
NSLog(#"JSON Error.");
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Could not contact server!" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"The download could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [news count];
}
NSString *_getString(id obj)
{
return [obj isKindOfClass:[NSString class]] ? obj : nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
}
cell.textLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:#"Issue"]);
cell.detailTextLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:#"Name"]);
return cell;
}
#end
How the JSON looks on the internet:
{
"Issues":[
{
"Issue":"2",
"Link":"google.com",
"Name":"Ios Test"
},
{
"Issue":"3",
"Link":"Yahoo",
"Name":"iOS test 2"
}
],
"success":1
}
Edit: sorry for not being clear in my question, The app does not crash but fails to load the data into the database in the log it puts this up:
2013-10-26 10:26:41.670 Westmount Procrastinator[2490:70b] JSON Error.
2013-10-26 10:26:41.671 Westmount Procrastinator[2490:70b] Server Data:
{"Issues":[{"Issue":"2","Link":"google.com","Name":"Ios Test"}],"success":1}
The goal of the application to contact a database download a list of Issues of a newspaper then list them in the list view.. Then allowing the user to click on the issues and download them.
Edit I added more to the JSON to help explain.
From your sample JSON structure it does not appear to be a NSArray. It is NSDictionary instead. So, while you are parsing JSON data save it in NSDictionary and not in NSArray. Also, change your IF condition afterwards.
Importantly, if your tableview is reading data from an NSArray of NSDictionaries then I would say put this NSDictionary into an NSArray and pass it to table view. Also, check from server side what is the output in case they are multiple dictionaries in which you need to handle accordingly. So essentially there are couple of more lines you need to induce here or else ask data provider (server side) to send NSArray in all cases.
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
if ([responseDict isKindOfClass:[NSDictionary class]]) {
NSArray *tableArray = [NSArray arrayWithArray:responseDict[#"Issues"]];
}
Now use tableArray to populate your table.
Issues is an array of dictionaries, so you should ask for the dictionary at the indexpath.row, then use objectForKey to pull the appropriate value from that dictionary.
NSDictionary *myDict = #{#"Issues": #[#{#"Issue": #"2",
#"Link": #"google.com",
#"Name": #"Ios Test"},
#{#"Issue": #"3",
#"Link": #"Yahoo",
#"Name": #"iOS test 2"}],
#"success": #"1"};
NSArray *issues = [myDict objectForKey:#"Issues"];
[issues enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"Issue: %# Link: %# Name: %#", [obj objectForKey:#"Issue"], [obj objectForKey:#"Link"], [obj objectForKey:#"Name"]);
}];
Will return:
2013-10-26 16:42:43.572 Jsontest[43803:303] Issue: 2 Link: google.com Name: Ios Test
2013-10-26 16:42:43.573 Jsontest[43803:303] Issue: 3 Link: Yahoo Name: iOS test 2