push data via segue without deleting previous data - ios

I have a table view controller with text fields that save using core data. I also have a search display view controller and i link them together using push segue and use another push with Prepareforsegue to link to information back to the same table view controller. But my issue is that the information is not saving back to the original table view controller but is creating a new one each time i call the prepare for segue.
Here is the table view controller code -
//
// PersonDetailTVC.m
// Staff Manager
//
// Created by Tim Roadley on 14/02/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "PersonDetailTVC.h"
#import "PersonsTVC.h"
#import <LibXL/LibXL.h>
#implementation PersonDetailTVC{
NSArray *recipes;
NSArray *searchResults;
UIImage *image;
UIImage *imagetwo;
UIImage *imagethree;
UIImage *imagefour;
UIImage *imagefive;
UIImage *imagesix;
UIImage *imageseven;
UIImage *imageeight;
UIImage *imagenine;
UIImage *imageten;
}
#synthesize delegate;
#synthesize person = _person;
#synthesize selectedRole;
#synthesize recipeLabel;
#synthesize recipeName;
#synthesize LinkLabel;
#synthesize personroomTextField = _personroomTextField;
#synthesize personFirstnameTextField = _personFirstnameTextField;
#synthesize personaddressTextField = _personaddressTextField;
#synthesize personcityTextField = _personcityTextField;
#synthesize personstateTextField = _personstateTextField;
#synthesize personstateTextField1 = _personstateTextField1;
#synthesize personzipTextField = _personzipTextField;
#synthesize personinsuranceTextField = _personinsuranceTextField;
#synthesize personclaimTextField = _personclaimTextField;
#synthesize persontaxTextField = _persontaxTextField;
#synthesize personRoleTableViewCell = _personRoleTableViewCell;
#synthesize personquantityTextField = _personquantityTextField;
#synthesize personageTextField = _personageTextField;
#synthesize persondescTextField = _persondescTextField;
#synthesize personserialTextField = _personserialTextField;
#synthesize personpriceTextField = _personpriceTextField;
#synthesize personnotesTextField = _personnotesTextField;
#synthesize personrcvperTextField = _personrcvperTextField;
#synthesize persontotaldepTextField = _persontotaldepTextField;
#synthesize personacvTextField = _personacvTextField;
#synthesize personconditionTextField = _personconditionTextField;
#synthesize personstoredImage = _personstoredImage;
#synthesize personimgThumbNail = _personimgThumbNail;
- (void)viewDidLoad
{
NSLog(#"Setting the value of fields in this static table to that of the passed Person");
self.personFirstnameTextField.text = self.person.firstname;
self.personaddressTextField.text = self.person.address;
self.personcityTextField.text = self.person.city;
self.personstateTextField.text = self.person.state;
self.personzipTextField.text = self.person.zip;
self.personinsuranceTextField.text = self.person.insurance;
self.personclaimTextField.text = self.person.claim;
self.persontaxTextField.text = self.person.tax;
self.personquantityTextField.text = self.person.quantity;
self.personRoleTableViewCell.textLabel.text = self.person.inRole.name;
self.personRoleTableViewCelltwo.textLabel.text = self.person.inRole.name;
self.personquantityTextField.text = self.person.quantity;
self.personconditionTextField.text = self.person.condition;
self.personageTextField.text = self.person.age;
self.persondescTextField.text = self.person.desc;
self.personserialTextField.text = self.person.serial;
self.personnotesTextField.text = self.person.notes;
self.personpriceTextField.text = self.person.price;
self.personrcvperTextField.text = self.person.rcvper;
self.personacvTextField.text = self.person.acv;
self.persontotaldepTextField.text = self.person.totaldep;
self.selectedRole = self.person.inRole; // ensure null role doesn't get saved.
self.selectedRoletwo = self.person.inRole; // ensure null role doesn't get saved.
self.personroomTextField.text = self.person.room;
self.personroomTextField1.text = self.person.room1;
self.personroomTextField2.text = self.person.room2;
self.personroomTextField3.text = self.person.room3;
self.personroomTextField4.text = self.person.room4;
self.personroomTextField5.text = self.person.room5;
self.personroomTextField6.text = self.person.room6;
self.personroomTextField7.text = self.person.room7;
self.personroomTextField8.text = self.person.room8;
self.personroomTextField9.text = self.person.room9;
self.personroomTextField10.text = self.person.room10;
self.title = self.recipe.name;
self.prepTimeLabel.text = self.recipe.prepTime;
self.recipeNameLabel.text = self.recipe.name;
self.LinkLabel.text = self.recipe.Link;
self.prepTimeLabel1.text = self.recipe.prepTime1;
self.recipeNameLabel1.text = self.recipe.name;
self.LinkLabel1.text = self.recipe.Link1;
self.persontotaldepTextField50.text = self.person.totaldep50;
self.selectedRole = self.person.inRole; // ensure null role doesn't get saved.
[self.tableView reloadData];
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(dismissKeyboard)];
[tgr setCancelsTouchesInView:NO];
[self.tableView addGestureRecognizer:tgr];
[super viewDidLoad];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showRecipeDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
PersonDetailTVC *destViewController = segue.destinationViewController;
destViewController.person = [recipes objectAtIndex:indexPath.row];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
switch (indexPath.row) {
case 0:
[self.personFirstnameTextField becomeFirstResponder];
break;
case 1:
[self.personaddressTextField becomeFirstResponder];
case 2:
[self.personcityTextField becomeFirstResponder];
case 3:
[self.personstateTextField becomeFirstResponder];
case 4:
[self.personzipTextField becomeFirstResponder];
case 6:
[self.personinsuranceTextField becomeFirstResponder];
case 7:
[self.personclaimTextField becomeFirstResponder];
case 8:
[self.persontaxTextField becomeFirstResponder];
case 9:
[self.personquantityTextField becomeFirstResponder];
case 10:
[self.personconditionTextField becomeFirstResponder];
case 11:
[self.personageTextField becomeFirstResponder];
case 12:
[self.persondescTextField becomeFirstResponder];
case 13:
[self.personserialTextField becomeFirstResponder];
case 14:
[self.personpriceTextField becomeFirstResponder];
case 15:
[self.personnotesTextField becomeFirstResponder];
case 16:
[self.personrcvperTextField becomeFirstResponder];
case 17:
[self.personacvTextField becomeFirstResponder];
case 18:
[self.persontotaldepTextField becomeFirstResponder];
case 19:
[self.personstoredImage becomeFirstResponder];
default:
break;
}
}
}
- (void)viewDidUnload
{
//[self setPersonNameTextField:nil];
[self setPersonFirstnameTextField:nil];
[self setPersonaddressTextField:nil];
[self setPersoncityTextField:nil];
[self setPersonstateTextField:nil];
[self setPersonzipTextField:nil];
[self setPersoninsuranceTextField:nil];
[self setPersonclaimTextField:nil];
[self setPersontaxTextField:nil];
[self setPersonquantityTextField:nil];
[self setPersonRoleTableViewCell:nil];
[self setPersonRoleTableViewCelltwo:nil];
[self setPersonconditionTextField:nil];
[self setPersonageTextField:nil];
[self setPersonserialTextField:nil];
[self setPersondescTextField:nil];
[self setPersonpriceTextField:nil];
[self setPersonnotesTextField:nil];
[self setPersonrcvperTextField:nil];
[self setPersontotaldepTextField:nil];
[self setPersonacvTextField:nil];
[super viewDidUnload];
NSString *fullURL = #"http://conecode.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];
}
- (IBAction)save:(id)sender
{
NSLog(#"Telling the PersonDetailTVC Delegate that Save was tapped on the PersonDetailTVC");
self.person.firstname = self.personFirstnameTextField.text; // Set Firstname
self.person.address = self.personaddressTextField.text; // Set Surname
self.person.city = self.personcityTextField.text;
self.person.state = self.personstateTextField.text;
self.person.zip = self.personzipTextField.text;
self.person.insurance = self.personinsuranceTextField.text;
self.person.claim = self.personclaimTextField.text;
self.person.tax = self.persontaxTextField.text;
self.person.quantity = self.personquantityTextField.text;
self.person.condition = self.personconditionTextField.text;
self.person.age = self.personageTextField.text;
self.person.desc = self.persondescTextField.text;
self.person.serial = self.personserialTextField.text;
self.person.price = self.personpriceTextField.text;
self.person.notes = self.personnotesTextField.text;
self.person.rcvper = self.personrcvperTextField.text;
self.person.acv = self.personacvTextField.text;
self.person.totaldep = self.persontotaldepTextField.text;
[self.persontwo setInRole:self.selectedRole]; // Set Relationship!!!
[self.persontwo.managedObjectContext save:nil]; // write to database
[self.delegate personDetailTVCDidSave:self];
[self.person setInRole:self.selectedRole]; // Set Relationship!!!
[self.person setInRole:self.selectedRoletwo];
[self.person.managedObjectContext save:nil]; // write to database
[self.delegate personDetailTVCDidSave:self];
}
- (void)dismissKeyboard {
[self.view endEditing:TRUE];
}
- (void)roleWasSelectedOnPersonRoleTVC:(PersonRoleTVC *)controller
{
self.personRoleTableViewCell.textLabel.text = controller.selectedRole.name;
self.selectedRole = controller.selectedRole;
NSLog(#"PersonDetailTVC reports that the %# role was selected on the PersonRoleTVC", controller.selectedRole.name);
[self.person setInRole:self.selectedRole];
[self.person.managedObjectContext save:nil];
[delegate personDetailTVCDidSave:self];
[controller.navigationController popViewControllerAnimated:YES];
self.personRoleTableViewCelltwo.textLabel.text = controller.selectedRole.name;
self.selectedRoletwo = controller.selectedRole;
NSLog(#"PersonDetailTVC reports that the %# role was selected on the PersonRoleTVC", controller.selectedRole.name);
[self.person setInRole:self.selectedRoletwo];
[self.person.managedObjectContext save:nil];
[delegate personDetailTVCDidSave:self];
[controller.navigationController popViewControllerAnimated:YES];
}
- (void)personChangedOnMaster:(PersonsTVC *)controller {
self.person = controller.selectedPerson;
NSLog(#"PersonDetailTVC.m: personChangedOnMaster: %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %#",self.person.firstname, self.person.address, self.person.city, self.person.state, self.person.zip, self.person.insurance, self.person.claim, self.person.tax, self.person.quantity, self.person.condition, self.person.age, self.person.desc, self.person.serial, self.person.price, self.person.notes, self.person.rcvper, self.person.totaldep,
self.person.serial1, self.person.price1, self.person.notes1, self.person.rcvper1, self.person.totaldep1,
self.person.serial2, self.person.price2, self.person.notes2, self.person.rcvper2, self.person.totaldep2,
self.person.serial3, self.person.price3, self.person.notes3, self.person.rcvper3, self.person.totaldep3,
self.person.serial4, self.person.price4, self.person.notes4, self.person.rcvper4, self.person.totaldep4,
self.person.serial5, self.person.price5, self.person.notes5, self.person.rcvper5, self.person.totaldep5,
self.person.serial6, self.person.price6, self.person.notes6, self.person.rcvper6, self.person.totaldep6,
self.person.serial7, self.person.price7, self.person.notes7, self.person.rcvper7, self.person.totaldep7,
self.person.serial8, self.person.price8, self.person.notes8, self.person.rcvper8, self.person.totaldep8,
self.person.serial9, self.person.price9, self.person.notes9, self.person.rcvper9, self.person.totaldep9,
self.person.serial10, self.person.price10, self.person.notes10, self.person.rcvper10, self.person.totaldep10,
self.person.room,
self.person.room1,
self.person.room2,
self.person.room3,
self.person.room4,
self.person.room5,
self.person.room6,
self.person.room7,
self.person.room8,
self.person.room9,
self.person.room10,
self.person.acv, self.person.storedImage);
[self.navigationController popViewControllerAnimated:YES]; // Return detail view to root.
[self viewDidLoad];
self.persontwo = controller.selectedPerson;
NSLog(#"PersonDetailTVC.m: personChangedOnMaster: %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# %# ",self.person.firstname, self.person.address, self.person.city, self.person.state, self.person.zip, self.person.insurance, self.person.claim, self.person.tax, self.person.quantity, self.person.condition, self.person.age, self.person.desc, self.person.serial, self.person.price, self.person.notes, self.person.rcvper, self.person.totaldep, self.person.acv, self.person.storedImage);
[self.navigationController popViewControllerAnimated:YES]; // Return detail view to root.
[self viewDidLoad];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
#end
Here is the search display controller code -
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showRecipeDetail"]) {
NSIndexPath *indexPath = nil;
Recipe *recipe = nil;
if (self.searchDisplayController.active) {
indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
recipe = [searchResults objectAtIndex:indexPath.row];
} else {
indexPath = [self.tableView indexPathForSelectedRow];
recipe = [recipes objectAtIndex:indexPath.row];
}
PersonDetailTVC *destViewController = segue.destinationViewController;
destViewController.recipe = recipe;
[self dismissViewControllerAnimated:YES completion:nil];
}
}

No need to pass data through the segue because when segue performs it always create new instance.
Add this in PersonDetailTVC.h
- (IBAction)backFromMapView:(UIStoryboardSegue *)segue
{
NSLog(#"and we are back");
PersonDetailTVC* person = (PersonDetailTVC *)segue.sourceViewController;
NSLog(#"location %#", person.recipe);
}
Helps you to how unwind segue performs.
this link is helpful how to the above more clearly:
IBOutlet does not display its value in UI

Related

Timer Object value is not passing through sender in an instance

This Application sends data (through a dictionary) two following instances to other views from the sender.
Home Page TableviewCell to each particular view according to each state
Ex- IF state 1 - AppointmentView 2 - OnthewayView 3 - TimerView 4 - Invoice View.
Home ---> Appointment
Home ---> ontheWay
Home ---> TimerView
Home ---> Invoice
Home ---> AppointmentView ---> ontheway --> timer ---> Invoice
I have an issue when I navigating timer --> Invoice the timer going as empty timer = "" so some of my functions (time fee calculation) are not working on this instance only.
But the same as 1st instance when I go back to Home and Home -> invoice timer=10 and rest of the functions works.
code snippet for 1st instance (the working one) (homeviewcontroller)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.section==0) {
if (bookingArray.count) {
NSInteger keyStatus =[bookingArray[indexPath.row][#"status"] integerValue] ;
switch (keyStatus) {
case 2:
[self performSegueWithIdentifier:#"appointmentDetail" sender:bookingArray[indexPath.row]];
break;
case 5:
[self performSegueWithIdentifier:#"ToMapController" sender:bookingArray[indexPath.row]];
break;
case 6:
[self performSegueWithIdentifier:#"ToTimerVC" sender:bookingArray[indexPath.row]];
break;
case 21:
[self performSegueWithIdentifier:#"ToTimerVC" sender:bookingArray[indexPath.row]];
break;
case 22:
[self performSegueWithIdentifier:#"ToInvoice" sender:bookingArray[indexPath.row]];
break;
}
Second instance (Not working) (timerViewController)
-(void)onTHEWAYButtonTapped
{
self.navigationItem.leftBarButtonItem.enabled = NO;
[[ProgressIndicator sharedInstance]showPIOnView:self.view withMessage:NSLocalizedString(#"Loading..",#"Loading..")];
switch (_bookingStatu) {
case 2:
case 5:
case 21:{
_bookingStatu = 6;
break;
}
case 6:{
_bookingStatu = 22;
break;
}
default:
break;
}
NSDictionary *parameters;
if (_bookingStatu==6) {
parameters = #{
kSMPcheckUserSessionToken: [[NSUserDefaults standardUserDefaults] objectForKey:KDAcheckUserSessionToken],
kSMPCommonDevideId :[[NSUserDefaults standardUserDefaults] objectForKey:kPMDDeviceIdKey],
#"ent_appnt_dt" :self.dictBookingDetails[#"apntDt"],
KSMPPatientEmail :self.dictBookingDetails[#"email"],
kSMPRespondResponse :[NSString stringWithFormat:#"%ld",(long)_bookingStatu],
#"ent_date_time" :[Helper getCurrentDateTime],
#"ent_bid" :self.dictBookingDetails[#"bid"],
#"bookingId" :_dictBookingDetails[#"bid"],
#"technicianId" :[[NSUserDefaults standardUserDefaults] objectForKey:#"ProviderId"],
#"latitude" :_dictBookingDetails[#"apptLat"],
#"longitude" :_dictBookingDetails[#"apptLong"]
//temp test
};
NSLog(#"Check the sent param-1%#",parameters);
}else if (_bookingStatu==22) {
parameters = #{
kSMPcheckUserSessionToken: [[NSUserDefaults standardUserDefaults] objectForKey:KDAcheckUserSessionToken],
kSMPCommonDevideId :[[NSUserDefaults standardUserDefaults] objectForKey:kPMDDeviceIdKey],
#"ent_appnt_dt" :self.dictBookingDetails[#"apntDt"],
KSMPPatientEmail :self.dictBookingDetails[#"email"],
kSMPRespondResponse :[NSString stringWithFormat:#"%ld",(long)_bookingStatu],
#"ent_date_time" :[Helper getCurrentDateTime],
#"ent_bid" :self.dictBookingDetails[#"bid"],
#"ent_timer":[NSString stringWithFormat:#"%d",(timeHr*3600)+(timeMin*60)+timeSec],
#"bookingId" :_dictBookingDetails[#"bid"],
#"technicianId" :[[NSUserDefaults standardUserDefaults] objectForKey:#"ProviderId"],
#"latitude" :_dictBookingDetails[#"apptLat"],
#"longitude" :_dictBookingDetails[#"apptLong"],
};
NSLog(#"Check the sent param-2%#",parameters);
}
NetworkHandler *handler = [NetworkHandler sharedInstance];
[handler composeRequestWithMethod:MethodupdateApptStatus
paramas:parameters
onComplition:^(BOOL succeeded, NSDictionary *response) {
[[ProgressIndicator sharedInstance]hideProgressIndicator];
[_customSliderView sliderImageOrigin];
if (succeeded) {
if ([response[#"errFlag"] isEqualToString:#"1"]) {
[Helper showAlertWithTitle:NSLocalizedString(#"Message", #"Message") Message:response[#"errMsg"]];
if([[response objectForKey:#"errNum"] intValue] == 41){
[Helper showAlertWithTitle:NSLocalizedString(#"Error",#"Error") Message:[response objectForKey:#"errMsg"]];
[self backButtonPressed];
}else if ([[response objectForKey:#"errNum"] intValue] == 83){
[self userSessionTokenExpire];
}
}else{
[self emitTheBookingACk:_bookingStatu];
[self updateCustomerinfo];
if (_bookingStatu==22) {
[self getTimerAPI];
[self performSegueWithIdentifier:#"toInvoiceSegue" sender:_dictBookingDetails];
}else if (_bookingStatu==6){
[self pauseTimer:nil];
}
}
}
else
{
NSLog(#"Error");
[[ProgressIndicator sharedInstance] hideProgressIndicator];
}
}];
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:#"toReportView"])
{
RecomReportViewController *reportView = (RecomReportViewController *)segue.destinationViewController;
reportView.bookingId = bookingID;
reportView.taskLocation = taskLocation;
}
else if([[segue identifier] isEqualToString:#"toInvoiceSegue"])
{
InvoiceViewController *details =[segue destinationViewController];
details.minutesCount=[NSString stringWithFormat:#"%d",(timeHr*3600)+(timeMin*60)+timeSec];
details.currentTimer = timerfinished;
[self getTimerAPI];
details.dictBookingDetails = sender;
}
return;
InvoiceViewController.m
—
- (void)viewDidLoad {
[super viewDidLoad];
//sending request to get materialfee
NSString *testTimer = _dictBookingDetails[#"timer"];
}
Please help me to find out the bug and fix the issue...

ios 8.3 BLE Device keeps disconnecting after connecting objective-c

I have a Shearwell stick reader, which reads in cattle tags, sheep tags and goat tags via BLE. When connecting the BLE device, the device list shows up in the tableView of the SDLBluetoothConnectViewController then disappears. I am also not able to grab the information from the device using a segue. The bluetooth icon flashes 3 times and does not pair with the device. Can anyone see where my error is i've looked for hours!! thanks in advance!
here is the SDLStickreader.m
// A StickReader is a wrapper for a CBPeripheral that has been discovered using a filter for StickReader UUID.
#import "SDLStickReader.h"
#import "SDLStickReaderManager.h"
#import "SDLStickReaderPrivate.h"
#import "SDLSerialPort.h"
//#import "SDLIdentifier.h"
#interface SDLStickReader () <SerialPortDelegate>
#property (strong, nonatomic) CBPeripheral *peripheral;
#end
#implementation SDLStickReader
static SDLStickReaderManager * _manager;
NSMutableData *_data;
SDLSerialPort *serialPort;
BOOL waitingForConfigInfo = YES;
NSMutableString *configString;
+(SDLStickReaderManager *)manager {
if (nil == _manager) {
_manager = [[SDLStickReaderManager alloc] init];
}
return _manager;
}
+ (instancetype)forPeripheral: (CBPeripheral *)peripheral {
return [[self alloc] initWithPeripheral:peripheral];
}
- (instancetype)initWithPeripheral: (CBPeripheral *)peripheral {
self = [super init];
if (self) {
_detail = #"";
self.peripheral = peripheral;
//peripheral.delegate = self;
__tagReadService = [CBUUID UUIDWithString:SDL_STICKREADER_TAGREAD_UUID];
if (peripheral.state == CBPeripheralStateConnected) {
NSLog(#"periperal is connected");
} else {
NSLog(#"periperal is NOT connected");
}
_data = [[NSMutableData alloc] init];
serialPort = [[SDLSerialPort alloc] initWithPeripheral:peripheral andDelegate:self];
peripheral.delegate = self;
[serialPort open ];
}
return self;
}
-(BOOL)hasPeripheral: (CBPeripheral *)peripheral {
return [self.peripheral isEqual: peripheral];
}
-(NSUUID *)identifier {
return self.peripheral.identifier;
}
-(NSString *)name {
return self.peripheral.name;
}
-(NSString *)description {
return [NSString stringWithFormat: #"Peripheral: %#", self.name];
}
-(NSString *)state {
switch (self.peripheral.state) {
case CBPeripheralStateConnected:
return SDL_STICKREADER_STATE_CONNECTED;
case CBPeripheralStateConnecting:
return SDL_STICKREADER_STATE_CONNECTING;
case CBPeripheralStateDisconnected:
return SDL_STICKREADER_STATE_DISCONNECTED;
}
}
// Every time the peripheral sends new data, it calls the delegate peripheral:didUpdateValueForCharacteristic:error: method. The second argument contains the characteristic that you can read.
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic: (CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
NSLog(#"Error");
return;
}
if ([self.characteristics containsObject: characteristic.UUID]) {
NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
// Have we got everything we need?
NSUInteger startOfEom = [stringFromData rangeOfString: SDL_STICKREADER_EOM].location;
if (NSNotFound == startOfEom) {
// it is not the EOM so append the data to what we have so far and wait for more.
[_data appendData: characteristic.value];
} else {
// contains EOM, so remove the
NSString *lastPart = [stringFromData substringToIndex:startOfEom];
NSString *message = [[NSString alloc] initWithData: _data encoding:NSUTF8StringEncoding];
if (nil != lastPart && lastPart.length > 0) {
message = [message stringByAppendingString:lastPart];
}
if (nil != self.listener) {
[self.listener stickReader:self didReadTag:message];
}
[_data setLength:0];
}
}
}
// Method that ensures that the CBCentral knows when a notification state for a given characteristic changes. Track it in order to understand when a characteristic state changes (update app values). You should check if the characteristic notification has stopped. If it has, you should disconnect from it:
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (![self.characteristics containsObject: characteristic.UUID]) {
return;
}
if (characteristic.isNotifying) {
NSLog(#"Notification began ");
} else {
// Notification has stopped
NSLog(#"Notification stopped ");
//[_manager cancelPeripheralConnection:peripheral];
}
}
/////////////////////////////////////////////////////////////////////////////////////
- (void) port: (SDLSerialPort*) serialPort event : (SPEvent) ev error: (NSInteger)err {
if (SP_EVT_OPEN == ev) {
//NSLog(#"serialPortOpened");
configString = [[NSMutableString alloc] init];
[serialPort write: [#"c\r" dataUsingEncoding: NSUTF8StringEncoding]];
} else {
NSLog(#"serialPortClosed");
}
}
- (void) writeComplete: (SDLSerialPort*) serialPort withError: (NSInteger)err {
NSLog(#"writeComplete");
}
- (void) port: (SDLSerialPort*) serialPort receivedData: (NSData*)data {
if (data.length > 0) {
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString: #"|()#"];
NSString *str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"receivedData: %#", str);
if ([str hasPrefix: #"Shearwell"]) {
_detail = str;
//NSLog(#"updating: %#", str);
[[SDLStickReader manager] addedShearwellStickReader: self];
} else if (NSNotFound != [str rangeOfCharacterFromSet: charSet].location ) {
// Data
if (waitingForConfigInfo) {
[configString appendString:str];
if (NSNotFound != [configString rangeOfString: #"(cS)"].location) {
// got end of config string, parse config.
NSRange found = [configString rangeOfString: #"#18|"];
if (NSNotFound != found.location) {
NSRange getRange = NSMakeRange(found.location + found.length, 1);
NSString *str = [configString substringWithRange: getRange];
self.eidFormat = [str integerValue];
NSLog(#"StickReader format: %d", self.eidFormat);
}
waitingForConfigInfo = NO;
[serialPort write: [#"v\r" dataUsingEncoding: NSUTF8StringEncoding]];
}
} else {
// Users data
[self.listener stickReader:self didReadData: str];
}
} else {
// Tag
if (nil != self.listener) {
[self.listener stickReader:self didReadTag: str];
}
}
}
}
and my SDLBluetoothConnectViewController.m
#import "SDLBluetoothConnectViewController.h"
#import "SDLStickReaderManager.h"
#import "SDLStickReader.h"
#import "SDLViewController.h"
#interface SDLBluetoothConnectViewController () <UITableViewDataSource, UITableViewDelegate, SDLStickReaderManagerListener>
#property (weak, nonatomic) IBOutlet UITableView *stickReaderListView;
#property (strong, nonatomic) IBOutlet UILabel *stickReaderNameLabel;
#property (strong, nonatomic) IBOutlet UILabel *stickReaderDescLabel;
#end
/*
This class starts the process of scanning in the 'viewDidLoad' method by setting the SDLStickReaderManager 'singleton' to self. When the scan button is pressed the SDLStickReaderManager scan is called, and each stick reader found is returned via the listener call. This listener call is used to refresh the table view.
When a user selects a stick reader from the list the StickReader view is started and passed the selected stick reader.
*/
#implementation SDLBluetoothConnectViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.stickReaderListView setDelegate: self];
[self.stickReaderListView setDataSource: self];
[SDLStickReader manager].listener = self;
[self.stickReaderListView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)scanButtonPressed:(id)sender {
[SDLStickReader.manager scan];
}
- (IBAction)cancelButtonPressed:(id)sender {
SDLStickReader.manager.listener = nil;
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)viewWillDisappear:(BOOL)animated {
/*
Every time the view disappears, you should stop the scanning process.
*/
[SDLStickReader.manager stopScan];
}
/////////////////////////////////////////////////////////////////////////////////
/////// Table handling //////////////////////////////////////////////////////////
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *stickReaders = SDLStickReader.manager.discoveredStickReaders;
SDLStickReader * stickReader = [stickReaders objectAtIndex: indexPath.row];
[SDLStickReader.manager stopScan];
[self performSegueWithIdentifier:#"deviceInfoSegue" sender:self];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *stickReaders = SDLStickReader.manager.discoveredStickReaders;
return stickReaders.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString * simpleTableIdentifier = #"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: simpleTableIdentifier];
if (nil == cell) {
cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: simpleTableIdentifier];
}
NSArray *stickReaders = SDLStickReader.manager.discoveredStickReaders;
SDLStickReader * stickReader = [stickReaders objectAtIndex: indexPath.row];
NSString *desc = [stickReader name];
cell.textLabel.text = desc;
return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"deviceInfoSegue"]) {
//some additional info here
}
}
////////////////////////////////////////////////////////////////////////////////// /
/// SDLStickReaderManager callbacks ///////////////////////////////////////////////
-(void)stickReader: (SDLStickReader *)stickReader addedToList: (NSArray *)discoveredStickReaders {
//NSLog(#"View StickReaderAdded");
[self.stickReaderListView reloadData];
//[SDLStickReader.manager connect: stickReader];
}
-(void)connectedStickReader: (SDLStickReader *)stickReader {
//NSLog(#"View StickReader connected");
[self.stickReaderListView reloadData];
}
-(void)disconnectedStickReader: (SDLStickReader *)stickReader {
//NSLog(#"View StickReader disconnected");
[self.stickReaderListView reloadData];
}

iOS Multiple UIpickerView not showing Arrays

I have a hidden UIpickerView that should display a different Array depending on what button is pushed. The picker view shows up when the button is pushed but for some reason it doesn't show the Arrays in the picker view. I would be extremely grateful of any help!!!!
Here is the .m file:
#import "ViewController.h"
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
#define GeoLocation TRUE // FALSE for no latitude/longitude information
#define kPICKERCOLUMN 1
typedef NS_ENUM(NSInteger, PickerType) {
CATEGORY_PICKER,
LOCATION_PICKER,
ORIGINATOR_PICKER,
DESTINATION_PICKER,
STATUS_PICKER
};
#define kPICKERCOLUMN 1
#define kPICKER_TAG 101
#interface ViewController ()
#end
#implementation ViewController
{
UIPickerView *picker;
PickerType pickerType;
}
#synthesize nameTextField, emailTextField, dateTextField, timeTextField, blankTextField, blankbTextField, mlabelcategory, messageTextView, categoryTypeBtn;
#synthesize name, emailaddress, date, time, blank, blankb, category, message, email, button;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
categoryTypes = [[NSArray alloc] initWithObjects:#"Appetizers",#"Breakfast",#"Dessert",#"Drinks",
#"Main Dish/Entree", #"Salad", #"Side Dish", #"Soup", #"Snack",
#"Baby Food", #"Pet Food",nil];
locationTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue"
,nil];
originatorTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
nil];
destinationTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
nil];
statusTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
nil];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
nameTextField.text = nil;
emailTextField.text = nil;
dateTextField.text = nil;
timeTextField.text = nil;
blankTextField.text = nil;
blankbTextField.text = nil;
mlabelcategory.text = nil;
messageTextView.text = nil;
picker = [[UIPickerView alloc] initWithFrame:CGRectMake(100,100,400,160)];
picker.showsSelectionIndicator = TRUE;
picker.dataSource = self;
picker.delegate = self;
picker.hidden = YES;
[self.view addSubview:picker];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)eve
{
picker.hidden = YES;
}
#pragma mark -
#pragma mark picker methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return kPICKERCOLUMN;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
switch (pickerType) {
case CATEGORY_PICKER:
return [categoryTypes count];;
break;
case LOCATION_PICKER:
return [locationTypes count];
break;
case ORIGINATOR_PICKER:
return [originatorTypes count];
break;
case DESTINATION_PICKER:
return [destinationTypes count];
break;
case STATUS_PICKER:
return [statusTypes count];
break;
default: return -1;
break;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
switch (pickerType) {
case CATEGORY_PICKER:
return [categoryTypes objectAtIndex:row];
break;
case LOCATION_PICKER:
return [locationTypes objectAtIndex:row];
break;
case ORIGINATOR_PICKER:
return [originatorTypes objectAtIndex:row];
break;
case DESTINATION_PICKER:
return [destinationTypes objectAtIndex:row];
break;
case STATUS_PICKER:
return [statusTypes objectAtIndex:row];
break;
default: return nil;
break;
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
switch (pickerType) {
case CATEGORY_PICKER: {
NSString *categoryType = [categoryTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[categoryTypeBtn setTitle:categoryType forState:UIControlStateNormal];
break;
}
case LOCATION_PICKER: {
NSString *locationType = [locationTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[locationTypeBtn setTitle:locationType forState:UIControlStateNormal];
break;
}
case ORIGINATOR_PICKER: {
NSString *originatorType = [originatorTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[originatorTypeBtn setTitle:originatorType forState:UIControlStateNormal];
break;
}
case DESTINATION_PICKER: {
NSString *destinationType = [destinationTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[destinationTypeBtn setTitle:destinationType forState:UIControlStateNormal];
break;
}
case STATUS_PICKER:{
NSString *statusType = [statusTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[statusTypeBtn setTitle:statusType forState:UIControlStateNormal];
break;
}
default:
break;
}
}
-(IBAction) showLocationTypePicker{
pickerType = LOCATION_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
-(IBAction) showCategoryTypePicker{
pickerType = CATEGORY_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
-(IBAction) showOriginatorTypePicker{
pickerType = ORIGINATOR_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
-(IBAction) showDestinationTypePicker{
pickerType = DESTINATION_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
-(IBAction) showStatusTypePicker{
pickerType = STATUS_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
#pragma - getting info from the UI
//NSString *test = nil;
- (IBAction)checkData:(id)sender
{
/*
name = nameTextField.text;
surname = surnameTextField.text;
bornDate = bornDateTextField.text;
address = addressTextField.text;
zipCode = zipTextField.text;
email = emailTextField.text;
*/
//NSLog(#" Name: %# \n Surname: %# \n Date of Birth: %# \n Address: %# \n Post Code: %# \n email: %# \n", name, surname, bornDate, address, zipCode, email);
unsigned int x,a = 0;
NSMutableString *emailmessage; //stringa variabile
emailmessage = [NSMutableString stringWithFormat: #""]; //le stringhe mutabili vanno inizializzate in questo modo!
for (x=0; x<7; x++)
{
switch (x) {
case 0:
if (nameTextField.text == nil) {
[emailmessage appendString:#"Name, "];
a=1;
}
break;
case 1:
if (emailTextField.text == nil)
{
[emailmessage appendString:#"Email Address, "];
a=1;
}
break;
case 2:
if (dateTextField.text == nil)
{
[emailmessage appendString:#"Date of Near Miss, "];
a=1;
}
break;
case 3:
if (timeTextField.text == nil)
{
[emailmessage appendString:#"Time of Near Miss, "];
a=1;
}
break;
case 4:
if (blankTextField.text == nil)
{
[emailmessage appendString:#"Post Code, "];
a=1;
}
break;
case 5:
if (blankbTextField.text == nil)
{
[emailmessage appendString:#"Email, "];
a=1;
}
break;
case 6:
if (mlabelcategory.text == nil)
{
[emailmessage appendString:#"Category, "];
a=1;
}
break;
case 7:
if (messageTextView.text == nil)
{
[emailmessage appendString:#"Observation Description, "];
a=1;
}
break;
default:
break;
}
}
NSLog (#"Email Message: %#", emailmessage);
if (a == 1) {
NSMutableString *popupError;
popupError = [NSMutableString stringWithFormat: #"Per inviare compilare i seguenti campi: "];
[popupError appendString:emailmessage]; //aggiungo i miei errori
[popupError appendString: #" grazie della comprensione."]; //
NSLog(#"%#", popupError);
UIAlertView *chiamataEffettuata = [[UIAlertView alloc]
initWithTitle:#"ATTENTION" //titolo del mio foglio
message:popupError
delegate:self
cancelButtonTitle:#"Ok, correggo" //bottone con cui si chiude il messaggio
otherButtonTitles:nil, nil];
[chiamataEffettuata show]; //istanza per mostrare effettivamente il messaggio
}
else
{
name = nameTextField.text;
emailaddress = emailTextField.text;
date = dateTextField.text;
time = timeTextField.text;
blank = blankTextField.text;
blankb = blankbTextField.text;
category = mlabelcategory.text;
message = messageTextView.text;
NSMutableString *nearmissreport;
nearmissreport = [NSMutableString stringWithFormat: #"<br><br> <b>Name:</b> %# <br> <b>Email Address:</b> %# <br> <b>Date of Near Miss:</b> %# <br> <b>Time of Near Miss:</b> %# <br> <b>Post Code:</b> %# <br> <b>Email Address:</b> %# <br> <b>Category:</b> %# <br><b>Observation Description:</b> %# <br>", name, emailaddress, date, time, blank, blankb, category, message];
NSLog(#"Near Miss Report: %#", nearmissreport);
NSMutableString *testoMail;
testoMail = [NSMutableString stringWithFormat: nearmissreport];
NSLog(#"%#", testoMail);
//MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject: name];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"paul.haddell#bbmmjv.com",nil];
//NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com",#"third#example.com", nil];
//NSArray *bccRecipients = [NSArray arrayWithObjects:#"four#example.com",nil];
[picker setToRecipients:toRecipients];
//[picker setCcRecipients:ccRecipients];
//[picker setBccRecipients:bccRecipients];
// Attach an image to the email.
//NSString *path = [[NSBundle mainBundle] pathForResource:#"ipodnano" ofType:#"png"];
//NSData *myData = [NSData dataWithContentsOfFile:path];
//[picker addAttachmentData:myData mimeType:#"image/png" fileName:#"ipodnano"];
// Fill out the email body text.
//NSMutableString *emailBody;
testoMail = [NSMutableString stringWithFormat: #"%#", testoMail];
[picker setMessageBody:testoMail isHTML:YES]; //HTML!!!!!!
// Present the mail composition interface.
[self presentViewController:picker animated:YES completion:nil];
}
}
// The mail compose view controller delegate method
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error
{
[self dismissModalViewControllerAnimated:YES];
}
#pragma mark - Mandare email
/*
- (void)sendMail:(NSMutableString*)testoMail{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Reclutamento pompieri"];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"reda.bousbah#gmail.com",nil];
//NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com",#"third#example.com", nil];
//NSArray *bccRecipients = [NSArray arrayWithObjects:#"four#example.com",nil];
[picker setToRecipients:toRecipients];
//[picker setCcRecipients:ccRecipients];
//[picker setBccRecipients:bccRecipients];
// Attach an image to the email.
//NSString *path = [[NSBundle mainBundle] pathForResource:#"ipodnano" ofType:#"png"];
//NSData *myData = [NSData dataWithContentsOfFile:path];
//[picker addAttachmentData:myData mimeType:#"image/png" fileName:#"ipodnano"];
// Fill out the email body text.
NSString *emailBody = #"It is raining in sunny California!";
[picker setMessageBody:emailBody isHTML:NO];
// Present the mail composition interface.
[self presentViewController:picker animated:YES completion:nil];
}
*/
#pragma mark - methods to control the keyboard
- (IBAction)backgroundTap:(id)sender //method for resign the keyboard when the background is tapped
{
[nameTextField resignFirstResponder];
[emailTextField resignFirstResponder];
[dateTextField resignFirstResponder];
[timeTextField resignFirstResponder];
[blankTextField resignFirstResponder];
[blankbTextField resignFirstResponder];
[mlabelcategory resignFirstResponder];
[messageTextView resignFirstResponder];
}
- (IBAction)doneButtonPressed:(id)sender
{
NSLog( #"done button pressed");
[sender resignFirstResponder];
}
#end
Many Thanks

IOS dev: Just need help in exc_bad_access error

Help, my app is showing thread 1 error exc_bad_access(code=1, address=0x2000001) on the last curly brace of my PlayViewController.
Note: this happen when I click the continue button on my GuessViewController. The continue button calls the the PlayViewController.
What i already did:
enabled ZOMBIE
close db
my GuessViewController:
#import "GuessViewController.h"
#import "PlayViewController.h"
#import "ViewController.h"
#interface GuessViewController ()
#end
#implementation GuessViewController
#synthesize userInput = _userInput;
#synthesize gword;
#synthesize gletter;
int score = 0;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_userInput.delegate = self;
self.scoreLabel.text = [NSString stringWithFormat:#"%d", score];
// Do any additional setup after loading the view.
}
-(void)touchesBegan:(NSSet*)touches withEvent: (UIEvent *) event{
[_userInput resignFirstResponder];
}
-(BOOL)textFieldShouldReturn: (UITextField*)textField {
if(textField){
[textField resignFirstResponder];
}
return NO;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)checkAnswer:(id)sender {
NSLog(#"%#", gword);
NSLog(#"%#", gletter);
NSString *temp = self.userInput.text;
unichar temp2 = [temp characterAtIndex: 0];
NSString *userletter= [NSString stringWithFormat:#"%C", temp2];
NSString *message1 = #"The word is ";
NSString *message2= [NSString stringWithFormat:#"%#", gword];
NSString *fm = [message1 stringByAppendingString:message2];
if([userletter isEqualToString:gletter]){
UIAlertView *checkAlert = [[UIAlertView alloc] initWithTitle:#"Got it Right" message:fm delegate:self cancelButtonTitle:#"Continue" otherButtonTitles:#"Back to Main Menu", nil];
score++;
self.scoreLabel.text = [NSString stringWithFormat:#"%d", score];
[checkAlert show];
}else{
UIAlertView *checkAlert = [[UIAlertView alloc] initWithTitle:#"Wrong" message:fm delegate:self cancelButtonTitle:#"Continue" otherButtonTitles:#"Back to Main Menu", nil];
[checkAlert show];
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex ==0){
PlayViewController *playViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"Play"];
[self presentViewController:playViewController animated:YES completion: Nil];
} else {
ViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:#"Main"];
[self presentViewController:viewController animated:YES completion: Nil];
}
}
#end
My PlayViewController:
#import "PlayViewController.h"
#import "GuessViewController.h"
#import <sqlite3.h>
#import "Word.h"
#interface PlayViewController ()
#end
#implementation PlayViewController
#synthesize thewords;
NSString *word;
NSTimer *myTimer;
int randomIndex;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[self wordList];
[super viewDidLoad];
// Do any additional setup after loading the view.
self.listChar.text = #" ";
int r = (arc4random()%[self.thewords count]);
word = [self.thewords objectAtIndex:r];
NSLog(#"%#", word);
randomIndex = (arc4random()%word.length);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)startGame:(id)sender {
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(listLetter:) userInfo:nil repeats:YES];
}
- (void)listLetter:(NSTimer *)timer
{
static int i = 0;
unichar letter;
if(randomIndex == i){
letter = ' ';
} else {
letter = [word characterAtIndex: i];
}
self.listChar.text = [NSString stringWithFormat:#"%C", letter];
if (++i == word.length) {
[timer invalidate];
i = 0;
GuessViewController *guessViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"Guess"];
//passing some data
guessViewController.word = word;
guessViewController.letter = [NSString stringWithFormat:#"%C", [word characterAtIndex: randomIndex]];
[self presentViewController:guessViewController animated:YES completion: Nil];
}
}
-(NSMutableArray *) wordList {
thewords = [[NSMutableArray alloc] initWithCapacity:26];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"LetterHunter.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success){
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)){
NSLog(#"An error has occured");
}
const char *sql = "SELECT * FROM WordList";
sqlite3_stmt*sqlStatement;
if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL)!=SQLITE_OK){
NSLog(#"Problem with prepare statement1");
} else {
while(sqlite3_step(sqlStatement) == SQLITE_ROW){
Word *word = [[Word alloc]init];
word.wordfromdb = [NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)];
[thewords addObject: word.wordfromdb];
}
}
sqlite3_finalize(sqlStatement);
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement2");
}
#finally {
sqlite3_close(db);
}
}
#end
As suggested below, I tried doing this instead but still there's the error
while(sqlite3_step(sqlStatement) == SQLITE_ROW){
NSString *temp = #"";
temp = [NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)];
[thewords addObject: temp;
}
From debug stack, it's a problem about autorelease. And I think the problem maybe in
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)){
I can't find db define. So I think it should be a instance property.
Try this:
DbClass *tempDb = nil;
if(!(sqlite3_open([dbPath UTF8String], &tempDb) == SQLITE_OK)){
self.db = tempDb;
What is wordfromdb? If it is string variable or any other datatype then add directly that into an array...
I think there is not need to create word object here as anyway your are not storing word object in array.
It looks to me an issue with word object. You are crating word object but adding its property only and not entire object.

I am getting an unauthorized error quickblox

I have the following code using quickblox.
Unfortunately, when I accessthe view controller, I get an "unAuthorized" error from quickblox API.
What am I doing wrong?
#import "QChatViewController.h"
#include "ChatMessageTableViewCell.h"
#interface QChatViewController ()
#end
#implementation QChatViewController
#synthesize opponent;
#synthesize currentRoom;
#synthesize messages;
#synthesize toolBar;
#synthesize sendMessageField;
#synthesize sendMessageButton;
#synthesize tableView;
#pragma mark -
#pragma mark View controller's lifecycle
- (id) initWithStartup: (NSDictionary *) _startup investor: (NSDictionary *) _investor chat_id: (NSInteger) _chat_id chat_name: (NSString *) _name
{
self = [self initWithNibName: #"QChatViewController" bundle: nil];
if(self)
{
startup = _startup;
investor = _investor;
startup_id = 0;
investor_id = 0;
if ([startup objectForKey: #"id"] &&
[startup objectForKey: #"id"] != (id)[NSNull null])
{
startup_id = [[startup objectForKey: #"id"] intValue];
}
if ([investor objectForKey: #"id"] &&
[investor objectForKey: #"id"] != (id)[NSNull null])
{
investor_id = [[investor objectForKey: #"id"] intValue];
}
past = 0;
chat_id = _chat_id;
self.title = _name;
self.title = #"Chat";
UIButton * button4 = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage * btnImage = [UIImage imageNamed: #"chatrightbtn.png"];
[button4 setFrame:CGRectMake(-90.0f, 0.0f, btnImage.size.width, btnImage.size.height)];
[button4 addTarget:self action:#selector(showSheet:) forControlEvents:UIControlEventTouchUpInside];
[button4 setImage: btnImage forState:UIControlStateNormal];
UIBarButtonItem *random1 = [[UIBarButtonItem alloc] initWithCustomView:button4];
self.navigationItem.rightBarButtonItem = random1;
self.navigationItem.leftBarButtonItem.title = #"";
}
return self;
}
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
QBASessionCreationRequest *extendedAuthRequest = [QBASessionCreationRequest request];
extendedAuthRequest.userLogin = #"testjk";
extendedAuthRequest.userPassword = #"jerry";
[QBAuth createSessionWithExtendedRequest:extendedAuthRequest delegate:self];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBarHidden = NO;
if(chat_id >= 1) {
NSString * roomName = [NSString stringWithFormat: #"%d", chat_id];
[[QBChat instance] createOrJoinRoomWithName: roomName membersOnly:YES persistent:NO];
}
messages = [[NSMutableArray alloc] init];
}
-(void) chatDidLogin{
// You have successfully signed in to QuickBlox Chat
}
- (void)completedWithResult:(Result *)result{
// Create session result
if(result.success && [result isKindOfClass:QBAAuthSessionCreationResult.class]){
// You have successfully created the session
QBAAuthSessionCreationResult *res = (QBAAuthSessionCreationResult *)result;
// Sign In to QuickBlox Chat
QBUUser *currentUser = [QBUUser user];
currentUser.ID = res.session.userID; // your current user's ID
currentUser.password = #"jerry"; // your current user's password
// set Chat delegate
[QBChat instance].delegate = self;
// login to Chat
[[QBChat instance] loginWithUser:currentUser];
}
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
// leave room
if(self.currentRoom){
if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {
// back button was pressed.
[[QBChat instance] leaveRoom:self.currentRoom];
[[DataManager shared].rooms removeObject:self.currentRoom];
}
}
}
- (void)viewDidUnload{
[self setToolBar:nil];
[self setSendMessageField:nil];
[self setSendMessageButton:nil];
[self setTableView:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)dealloc {
}
- (IBAction)sendMessage:(id)sender {
if(self.sendMessageField.text.length == 0){
return;
}
if(chat_id == 0)
{
NSString * sid = [NSString stringWithFormat: #"%d", startup_id];
NSString * iid = [NSString stringWithFormat: #"%d", investor_id];
NSString * pasts = [NSString stringWithFormat: #"%d", past];
NSString * chat_ids = [NSString stringWithFormat: #"%d", chat_id];
NSString * path_str = [NSString stringWithFormat: #"chats/?format=json"];
NSMutableDictionary* params =[NSMutableDictionary dictionaryWithObjectsAndKeys:
sid, #"startup",
iid, #"investor",
pasts, #"past",
chat_ids, #"conversation_id",
#"avv7ejtaegxxk2wzgnymsj8xtm2tk9s4xgp6854r6dqn8bk6jjwux4g9dh9b", #"apikey",
nil];
[[API sharedInstance] postcommandWithParams:params
path: path_str
onCompletion:^(NSDictionary *json)
{
if(chat_id == 0)
{
if ([json objectForKey: #"id"] &&
[json objectForKey: #"id"] != (id)[NSNull null])
{
chat_id = [[json objectForKey: #"id"] intValue];
if(chat_id >= 1) {
NSString * roomName = [NSString stringWithFormat: #"%d", chat_id];
[[QBChat instance] createOrJoinRoomWithName: roomName membersOnly:YES persistent:NO];
}
[[QBChat instance] sendMessage:self.sendMessageField.text toRoom:self.currentRoom];
// reload table
[self.tableView reloadData];
// hide keyboard & clean text field
[self.sendMessageField resignFirstResponder];
[self.sendMessageField setText:nil];
}
}
}];
}
else
{
[[QBChat instance] sendMessage:self.sendMessageField.text toRoom:self.currentRoom];
// reload table
[self.tableView reloadData];
// hide keyboard & clean text field
[self.sendMessageField resignFirstResponder];
[self.sendMessageField setText:nil];
}
}
-(void)keyboardShow{
CGRect rectFild = self.sendMessageField.frame;
rectFild.origin.y -= 215;
CGRect rectButton = self.sendMessageButton.frame;
rectButton.origin.y -= 215;
[UIView animateWithDuration:0.25f
animations:^{
[self.sendMessageField setFrame:rectFild];
[self.sendMessageButton setFrame:rectButton];
}
];
}
-(void)keyboardHide{
CGRect rectFild = self.sendMessageField.frame;
rectFild.origin.y += 215;
CGRect rectButton = self.sendMessageButton.frame;
rectButton.origin.y += 215;
[UIView animateWithDuration:0.25f
animations:^{
[self.sendMessageField setFrame:rectFild];
[self.sendMessageButton setFrame:rectButton];
}
];
}
#pragma mark -
#pragma mark TextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
[self keyboardShow];
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
[self keyboardHide];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField setText:nil];
[textField resignFirstResponder];
return YES;
}
#pragma mark -
#pragma mark TableViewDataSource & TableViewDelegate
static CGFloat padding = 20.0;
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"MessageCellIdentifier";
// Create cell
ChatMessageTableViewCell *cell = (ChatMessageTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[ChatMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
cell.accessoryType = UITableViewCellAccessoryNone;
cell.userInteractionEnabled = NO;
// Message
QBChatMessage *messageBody = [messages objectAtIndex:[indexPath row]];
// set message's text
NSString *message = [messageBody text];
cell.message.text = message;
// message's datetime
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: #"yyyy-mm-dd HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
NSString *time = [formatter stringFromDate:messageBody.datetime];
CGSize textSize = { 260.0, 10000.0 };
CGSize size = [message sizeWithFont:[UIFont boldSystemFontOfSize:13]
constrainedToSize:textSize
lineBreakMode:UILineBreakModeWordWrap];
size.width += (padding/2);
// Left/Right bubble
UIImage *bgImage = nil;
if ([[[DataManager shared] currentUser] ID] == messageBody.senderID || self.currentRoom) {
bgImage = [[UIImage imageNamed:#"orange.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
[cell.message setFrame:CGRectMake(padding, padding*2, size.width+padding, size.height+padding)];
[cell.backgroundImageView setFrame:CGRectMake( cell.message.frame.origin.x - padding/2,
cell.message.frame.origin.y - padding/2,
size.width+padding,
size.height+padding)];
cell.date.textAlignment = UITextAlignmentLeft;
cell.backgroundImageView.image = bgImage;
if(self.currentRoom){
cell.date.text = [NSString stringWithFormat:#"%d %#", messageBody.senderID, time];
}else{
cell.date.text = [NSString stringWithFormat:#"%# %#", [[[DataManager shared] currentUser] login], time];
}
} else {
bgImage = [[UIImage imageNamed:#"aqua.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
[cell.message setFrame:CGRectMake(320 - size.width - padding,
padding*2,
size.width+padding,
size.height+padding)];
[cell.backgroundImageView setFrame:CGRectMake(cell.message.frame.origin.x - padding/2,
cell.message.frame.origin.y - padding/2,
size.width+padding,
size.height+padding)];
cell.date.textAlignment = UITextAlignmentRight;
cell.backgroundImageView.image = bgImage;
cell.date.text = [NSString stringWithFormat:#"%# %#", self.opponent.login, time];
}
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [self.messages count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
QBChatMessage *chatMessage = (QBChatMessage *)[messages objectAtIndex:indexPath.row];
NSString *text = chatMessage.text;
CGSize textSize = { 260.0, 10000.0 };
CGSize size = [text sizeWithFont:[UIFont boldSystemFontOfSize:13]
constrainedToSize:textSize
lineBreakMode:UILineBreakModeWordWrap];
size.height += padding;
return size.height+padding+5;
}
#pragma mark -
#pragma mark QBChatDelegate
// Did receive 1-1 message
- (void)chatDidReceiveMessage:(QBChatMessage *)message{
[self.messages addObject:message];
// save message to cache if this 1-1 chat
if (self.opponent) {
[[DataManager shared] saveMessage:[NSKeyedArchiver archivedDataWithRootObject:messages]
toHistoryWithOpponentID:self.opponent.ID];
}
// reload table
[self.tableView reloadData];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[messages count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
// Did receive message in room
- (void)chatRoomDidReceiveMessage:(QBChatMessage *)message fromRoom:(NSString *)roomName{
// save message
[self.messages addObject:message];
// reload table
[self.tableView reloadData];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[messages count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
// Fired when you did leave room
- (void)chatRoomDidLeave:(NSString *)roomName{
NSLog(#"Chat Controller chatRoomDidLeave");
}
// Called in case changing occupant
- (void)chatRoomDidChangeOnlineUsers:(NSArray *)onlineUsers room:(NSString *)roomName{
NSLog(#"chatRoomDidChangeOnlineUsers %#, %#",roomName, onlineUsers);
}
- (void)chatRoomDidEnter:(QBChatRoom *)room{
NSLog(#"Private room %# was created", room.name);
// You have to retain created room if this is temporary room. In other cases room will be destroyed and all occupants will be disconnected from room
self.currentRoom = room;
// Add users to this room
NSInteger user_id = [[[[API sharedInstance] user] objectForKey: #"id"] intValue];
NSNumber *me = [NSNumber numberWithInt: user_id];
NSArray *users = [NSArray arrayWithObjects: me, nil];
[[QBChat instance] addUsers:users toRoom:room];
}
#end
I'm not sure that you have user with these credentials
extendedAuthRequest.userLogin = #"testjk";
extendedAuthRequest.userPassword = #"jerry";
I first check user exist or not modified your code like this...
//your code
.....
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
//Create extended session request with user authorization
QBASessionCreationRequest *extendedAuthRequest = [QBASessionCreationRequest request];
//Check user exist or not
if(self.currentQBUser){
extendedAuthRequest.userLogin = #"testjk";
extendedAuthRequest.userPassword = #"testjk";
}
[QBAuth createSessionWithExtendedRequest:extendedAuthRequest delegate:self];
}
........
- (void)completedWithResult:(Result *)result{
// Create session result
if(result.success && [result isKindOfClass:QBAAuthSessionCreationResult.class]){
// Register new user
self.currentQBUser = [[QBUUser alloc] init];
user.fullName = #"Your Name";
user.login = #"testjk";
user.password = #"testjk";
user.tags = [NSMutableArray arrayWithObject:#"Chat"];
// Create user
[QBUsers signUp:user delegate:self];
// You have successfully created the session
QBAAuthSessionCreationResult *res = (QBAAuthSessionCreationResult *)result;
} else if([result isKindOfClass:[QBUUserLogInResult class]]){
if(result.success){
QBUUserLogInResult *res = (QBUUserLogInResult *)result;
//Now login to chat
// Sign In to QuickBlox Chat
QBUUser *currentUser = res.user;
currentUser.ID = #"testjk; // your current user's ID
currentUser.password = #"testjk"; // same as user id
// set Chat delegate
[QBChat instance].delegate = self;
// login to Chat
[[QBChat instance] loginWithUser:currentUser];
}
}
if (result.errors.count && (401 != result.status))
{
NSLog(#"QBErrors: %#",result.errors);
}
}
I met the same problem here. And i gave the way i made it.
error unauthorized is the user.login or user.password.
user.login can not be email address but your login username. these i do not know why.
user.password is the email address/username password.
check these informations in your User list at QuickBlox Dashboard
Hope these instructions will help.
use quickblox.min.js
var QBApp = {
appId: 123,
authKey: 'dfdgfd44444',
authSecret: 'dffdgfdg455445'
};
$(document).ready(function () {
QB.init(QBApp.appId, QBApp.authKey, QBApp.authSecret);
QB.createSession(function (err, result) {
console.log('Session create callback', err, result);
});
})
function addUser() {
var pwd, ctr, data;
ctr = document.getElementById(myForm.password);
pwd = ctr.value;
var params = { 'login': 'Rajesh', 'password': 'Pass#123' };
alert(params)
QB.users.create(params, function (err, user) {
debugger;
if (user) {
alert('Done')
//$('#output_place').val(JSON.stringify(user));
} else {
alert('Error')
//$('#output_place').val(JSON.stringify(err));
}
})}

Resources