Obj-C UITable not populating with MutableArray - ios

I have an array that loads when the app starts and it gets the correct data and fills the array but once I go to the tableviewcontroller it says the array is null.
This is where I get the data
AppDelegate.h
#interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSMutableArray *tableDicsArrayTickets;
NSMutableArray *dictionaryStack;
NSMutableString *textInProgress;
NSError *errorPointer;
}
#property (strong, nonatomic) NSMutableArray *tableDicsArrayTickets;
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) NSString *photo_URL;
+(NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)errorPointer;
+(NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)errorPointer;
+(AppDelegate *) getInstance;
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
self.tableDicsArrayTickets = [[NSMutableArray alloc] init];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:#"http://MYURLexample.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *deviceCode = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSString *post = [[NSString alloc] initWithFormat:#"parameter=%#", deviceCode];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
NSString *text =[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
NSDictionary *dics = [[NSDictionary alloc]initWithDictionary:[AppDelegate dictionaryForXMLString:text error:nil]];
NSLog(#"dics is %#", dics);
[self.tableDicsArrayTickets addObject:[[dics valueForKey:#"response"] valueForKey:#"text"]];
NSLog(#"Array2 is %#", self.tableDicsArrayTickets);
}
}];
[dataTask resume];
ViewController.h
#interface HistoryViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>
{
AppDelegate *mainDelegate;
}
#property (strong, nonatomic) AppDelegate *mainDelegate;
ViewController.m
#pragma
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [mainDelegate.tableDicsArrayTickets count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 60;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableArray *array = mainDelegate.tableDicsArrayTickets;
NSString *cellIdentifier = #"Cell";
PhotoTableViewCell *cell = (PhotoTableViewCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil)
{
cell = [[PhotoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
NSLog(#"Array is %#", [[array objectAtIndex:indexPath.row] objectForKey:#"text"]);
cell.ticketNumber.text = [[array objectAtIndex:indexPath.row] objectForKey:#"text"];
return cell;
}
Im not having a problem getting the data for the array its just once I finally go to the view controller with the table on it the array becomes null.

I think you're doing a number of things wrong...
First:
// AppDelegate.h
#interface AppDelegate : UIResponder <UIApplicationDelegate>
{
// this should NOT be here
NSMutableArray *tableDicsArrayTickets;
NSMutableArray *dictionaryStack;
NSMutableString *textInProgress;
NSError *errorPointer;
}
#property (strong, nonatomic) NSMutableArray *tableDicsArrayTickets;
// ...
That should give you a compile warning:
autosynthesized property 'tableDicsArrayTickets' will use synthesized instance
variable '_tableDicsArrayTickets', not existing instance variable 'tableDicsArrayTickets'
Same with:
//HistoryViewController.h
#interface HistoryViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>
{
// this should NOT be here
AppDelegate *mainDelegate;
}
#property (strong, nonatomic) AppDelegate *mainDelegate;
Which should give you:
autosynthesized property 'mainDelegate' will use synthesized instance
variable '_mainDelegate', not existing instance variable 'mainDelegate'
Then, you're not showing where you have this in HistoryViewController.m (should probably be in viewDidLoad()):
_mainDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

Related

Getting a json file from a website into UITableview with Objective C

I'm attempting to get a json file from a website into UITableview with Objective C.
As I'm not an advanced coder please excuse my crude coding tecniques.
I have a .json file uploaded to my webspace. The File is formatted as so:
"JSONDATA":[
{
"name": "ABC",
"details": "DEF"
},
{
"name": "UVW",
"details": "XYZ"
}
]
my .h looks like:
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
IBOutlet UITableView *myTableView;
}
#property (strong, nonatomic) IBOutlet UITableView *myTableView;
#end
the .m code
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrName;
NSMutableArray *arrDetails;
NSString *responseString;
}
#end
#implementation ViewController
#synthesize myTableView;
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"ViewDidLoad");
[self fetchData];
[myTableView reloadData];
}
-(void)fetchData
{
NSLog(#"GetJsonResponse Fired");
NSURL *URL = [NSURL URLWithString:#"http://myWebsite.com/json/myJsonFile.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSLog(#"URLRequest = %#",request);
/////////////////////////////////////////////////////////////////// Nothing Below Here Fires/////////////////////////////////////////////////
// [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:ourBlock];
[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error)
{
// Block Body
NSLog(#"response = %#",response);
NSLog(#"block Body");
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"GetJsonDict%#",jsonDict);
NSArray *arr = jsonDict[#"JSONFILE"];
NSLog(#"jasoDict = %#",arr);
self->arrName = [[NSMutableArray alloc]init];
self->arrDetails = [[NSMutableArray alloc]init];
//arrValue = [[NSMutableArray alloc]init];
for(int i=0;i<[arr count];i++)
{
NSString *strName = [arr[i]objectForKey:#"NAME"];
NSString *strCode = [arr[i]objectForKey:#"CODE"];
// NSString *strValue = [arr[i]objectForKey:#"VALUE"];
NSLog(#"The strName is - %#",strName);
NSLog(#"The strCode is - %#", strCode);
// NSLog(#"The strValue is - %#", strValue);
[self->arrName addObject:strName];
[self->arrDetails addObject:strCode];
// [arrValue addObject:strValue];
NSLog(#"The arrName is - %#",self->arrName);
NSLog(#"The arrDetails is - %#", self->arrDetails);
// NSLog(#"The arrValue is - %#", arrValue);
}
}];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrName.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strCell = #"Cell";
// UITableViewCell *cell = [UITableView dequeueReusableCellWithIdentifier:strCell];
UITableViewCell *cell = [myTableView dequeueReusableCellWithIdentifier:strCell forIndexPath:indexPath];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strCell];
}
cell.textLabel.text = arrName[indexPath.row];
cell.detailTextLabel.text = arrDetails[indexPath.row];
return cell;
}
#end
I can't seem to put all the pieces together and get any data through to parse.
The NSLog is telling me:
2020-03-09 14:13:42.605558-0500 jsonFromWeb[27389:1317924] ViewDidLoad
2020-03-09 14:13:42.605802-0500 jsonFromWeb[27389:1317924] GetJsonResponse Fired
2020-03-09 14:13:42.606118-0500 jsonFromWeb[27389:1317924] URLRequest = <NSURLRequest: 0x6000001f8cc0> { URL: http://mywebsite.com/json/myJsonFile.json }
Where is this thing derailing? I can't get any data out of the URLResponse.
Thanks so much.
You have to resume the data task and you have to reload the table view inside the completion block on the main thread
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
...
}
dispatch_async(dispatch_get_main_queue(), ^{
[myTableView reloadData];
});
}] resume];

Objective c iOS passing data

hi I am new to iOS and below is my code I have to pass the top that I get from request reply...please help me I am stuck here
first view controller is otp view second vc is verifyviewcontroller
Otp view c.h
#import <UIKit/UIKit.h>
#interface OtpViewController : UIViewController
#property (nonatomic, retain) NSString *str;
#end
otpviewcontroller.m
#import "OtpViewController.h"
#import "VerifyViewController.h"
#interface OtpViewController () <VerifyViewControllerDelegate>
#property (weak, nonatomic) IBOutlet UIImageView *bbi;
#property (weak, nonatomic) IBOutlet UIButton *submittf;
#property (weak, nonatomic) IBOutlet UITextField *mobiletf;
#property (weak,nonatomic) NSArray *tmp;
#property(weak,nonatomic) NSString *requestReply ;
//#property(weak,nonatomic) NSDictionary *A;
#end
#implementation OtpViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background"]];
NSLog(#"viewDidLoad");
[super viewDidLoad];
}
- (IBAction)submitb:(id)sender
{
if (_mobiletf.text && _mobiletf.text.length >0 )
{
/* not empty - do something */
NSString *post = [NSString stringWithFormat:#"phone=%#",_mobiletf.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Next up, we read the postData's length, so we can pass it along in the request.
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.sitesandflats.com/send_otp.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSLog(#"the data Details is %#", post);
// And finally, we can send our request, and read the reply by creating a new NSURLSession:
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
NSString *str=requestReply;
VerifyViewController *vc = [[VerifyViewController alloc] init];
NSString *tmp=requestReply;
NSLog(#"%#",str);
NSLog(#"%#",_tmp);
}] resume];
[ self performSegueWithIdentifier:#"b1" sender:self];
}
else
{
/* what ever */
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Please check your input!!."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender{
VerifyViewController *loadCtr = (VerifyViewController *)segue.destinationViewController;
loadCtr.delegate = self;
loadCtr.tmpStr = (#"otp: %#",_tmp);
NSLog(#"passing val: %#",_tmp);
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
Verify view controller.h
#import <UIKit/UIKit.h>
#protocol VerifyViewControllerDelegate <NSObject>
-(void)moveToA:(NSString *)str;
#end
#interface VerifyViewController : UIViewController
#property (nonatomic, copy) NSString *tmpStr;
#property (nonatomic, assign) id <VerifyViewControllerDelegate> delegate;
//#property (nonatomic, strong) OtpViewController *received;
//#property (strong, nonatomic) IBOutlet UITextField *textDisplay;
#property(nonatomic,weak) NSMutableArray *myAray;
#property(nonatomic,strong) NSString *object;
#property(strong,nonatomic) NSString *tmp1;
#end
Verify view controller.m
#import "VerifyViewController.h"
#import "OtpViewController.h"
#interface VerifyViewController ()
#property (weak, nonatomic) IBOutlet UITextField *otptf;
#property (weak, nonatomic) IBOutlet UIButton *submitb;
//#property (weak,nonatomic) textDisplay;
//#property (weak,nonatomic) NSString *received;
#end
#implementation VerifyViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background"]];
// Do any additional setup after loading the view.
}
- (IBAction)submitb:(id)sender {
NSLog(#"%#",_tmpStr);
if(_otptf.text==_tmpStr)
{
[self performSegueWithIdentifier:#"b2" sender:self];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Incorrect otp please check the input!!!."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
at nslog I get reply as ("success":"1";"otp":"985123") I need this otp to store and verify in next page please help
First you need to change property
From
#property (weak,nonatomic) NSArray *tmp;
To
#property (strong,nonatomic) NSStirng *tmp;
Assign value to tmp as below
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
NSLog(#"requestReply: %#", jsonDict);
self.tmp=[jsonDict valueForKey:#"otp"] ; // you need to extract value using the key [requestReply valueForKey:#"otp"];
NSLog(#"%#",self.tmp);
}] resume];
Pass tmp to VerifyVIewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender{
VerifyViewController *loadCtr = (VerifyViewController *)segue.destinationViewController;
loadCtr.delegate = self;
loadCtr.tmpStr = self.tmp;
NSLog(#"passing val: %#",_tmp);
}

Google Translate API on iPhone

I am writing a simple code, in which I am using Google API for translation services, but I am getting the following error:
Connection failed: Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x176c80a0 {NSUnderlyingError=0x175c8d00 "bad URL", NSLocalizedDescription=bad URL}
This is the code I have written:
#import "ViewController.h"
#import"SBJson.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UITextField *textfield;
#property (strong, nonatomic) IBOutlet UIButton *go;
#property (strong, nonatomic) IBOutlet UITextView *textview;
- (IBAction)translate:(id)sender;
#property (strong, nonatomic) NSMutableArray *translations;
#property (strong, nonatomic)NSString *_lastText;
#property (nonatomic, copy) NSString * lastText;
#end
#implementation ViewController
#synthesize lastText = _lastText;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//Initializing the translation array
_translations = [[NSMutableArray alloc] init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)performTranslation {
responseData = [[NSMutableData data] init ];
NSString *langString = #"en|ja";
NSString *textEscaped = [_lastText
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *langStringEscaped = [langString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//My_Key=Google generated key
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/language/translate/v2?
key={My_key}&source=en&target=de&q=%#",textEscaped];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (IBAction)translate:(id)sender {
[_translations removeAllObjects];
[_textfield resignFirstResponder];
_go.enabled=NO;
self.lastText = _textfield.text;
[_translations addObject:_lastText];
_textview.text = _lastText;
[self performTranslation];
}
- (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 {
_textview.text = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
_go.enabled = YES;
NSLog([NSString stringWithFormat:#"Connection failed: %#", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSMutableDictionary *luckyNumbers = [responseString JSONValue];
if (luckyNumbers != nil) {
NSDecimalNumber * responseStatus = [luckyNumbers objectForKey:#"responseStatus"];
if ([responseStatus intValue] != 200) {
_go.enabled = YES;
return;
}
NSMutableDictionary *responseDataDict = [luckyNumbers objectForKey:#"responseData"];
if (responseDataDict != nil) {
NSString *translatedText = [responseDataDict objectForKey:#"translatedText"];
[_translations addObject:translatedText];
self.lastText = translatedText;
_textview.text = [_textview.text stringByAppendingFormat:#"\n%#", translatedText];
_go.enabled = YES;
}
}
}
#end
The problem is like it says. The URL has been generated incorrectly. Try:
NSString * source = #"en";
NSString * target = #"ja";
NSString * key = #"YOUR-KEY";
NSString * url = [NSString stringWithFormat:#"https://www.googleapis.com/language/translate/v2?key=%#&source=%#&target=%#",key,source,target];
and see what response you get.
You can just use FGTranslator. Simple.
FGTranslator *translator = [[FGTranslator alloc] initWithGoogleAPIKey:#"your_google_key"];
[translator translateText:#"Bonjour!"
completion:^(NSError *error, NSString *translated, NSString *sourceLanguage)
{
if (error)
NSLog(#"translation failed with error: %#", error);
else
NSLog(#"translated from %#: %#", sourceLanguage, translated);
}];

Can't reload data in tableView after parsing XML

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;

NSUrlConnection doesnt seem to be working,

I'm trying to use googletts converted and seem to be running into trouble. I think I made the class correctly in terms of structure. But I dont think the NSURLConnection is returning any useful data. Can someone please help me check if its working and if not why?
In the connectiondidfinishloading section I am checking download length
NSLog(#"hmmmm %lu", (unsigned long)[downloadedData length])
which is returning 0. Thats why I think its not working.
The goal is to have the app speak what is downloaded
Thanks!!!
I just have a button in my view controller that launches everything
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "RJGoogleTTS.h"
#interface ViewController : UIViewController <CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet UILabel *userLabel;
#property (strong, nonatomic) CLLocationManager *locationManager;
#property (strong, nonatomic) CLGeocoder *geoCoder;
#property (strong, nonatomic) RJGoogleTTS *googleTTS;
- (IBAction)geoCodeLocation:(id)sender;
- (IBAction)rjGoogleButton:(id)sender;
#end
here is the implementation file
- (IBAction)rjGoogleButton:(id)sender {
googleTTS = [[RJGoogleTTS alloc]init];
[googleTTS convertTextToSpeech:#"How are you today user?"];
}
RJGoogleTTS.h
#import <Foundation/Foundation.h>
#protocol RJGoogleTTSDelegate <NSObject>
#required
- (void)receivedAudio:(NSMutableData *)data;
- (void)sentAudioRequest;
#end
#interface RJGoogleTTS : NSObject {
id <RJGoogleTTSDelegate> delegate;
NSMutableData *downloadedData;
}
#property (nonatomic, retain) id <RJGoogleTTSDelegate> delegate;
#property (nonatomic, retain) NSMutableData *downloadedData;
- (void)convertTextToSpeech:(NSString *)searchString;
#end
.m
#import "RJGoogleTTS.h"
#import <AVFoundation/AVFoundation.h>
#implementation RJGoogleTTS
#synthesize delegate, downloadedData;
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
- (void)convertTextToSpeech:(NSString *)searchString {
NSString *search = [NSString stringWithFormat:#"http://translate.google.com/translate_tts?q=%#", searchString];
search = [search stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSLog(#"Search: %#", search);
self.downloadedData = [[NSMutableData alloc] initWithLength:0];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:search]];
[request setValue:#"Mozilla/5.0" forHTTPHeaderField:#"User-Agent"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
[delegate sentAudioRequest];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"did you receive response user");
[self.downloadedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"did you receive data user");
[self.downloadedData appendData:data];
// AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]initWithData:downloadedData error:nil];
// [audioPlayer play];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Failure");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"it worked user!!!");
[delegate receivedAudio:self.downloadedData];
NSLog(#"hmmmm %d", [self.downloadedData length]);
// NSString *txt = [[NSString alloc] initWithData:downloadedData encoding: NSASCIIStringEncoding];
// NSLog(#"%#hello",txt);
}
#end
Remember that this is happening asynchronously. You set the size of downloadedData to 0 after your call the NSURLConnection.
Move:
self.downloadedData = [[NSMutableData alloc] initWithLength:0];
before your call to NSURLConnection.
There's nothing wrong with your NSURLConnection methods. Your search string is wrong. It should be:
NSString *search = [NSString stringWithFormat:#"http://translate.google.com/translate_tts?tl=en&q=%#",searchString];
You didn't start the URLConnection. Change [[NSURLConnection alloc] initWithRequest:request delegate:self]; like this [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

Resources