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...
Related
I am trying to call using Twilio sdk but my call is disconnected in 2 or 3 seconds. My Twilio account is upgrated. I am using below code
-(IBAction)mainButtonPressed:(id)sender
{
BasicPhoneAppDelegate* delegate = (BasicPhoneAppDelegate*)[UIApplication sharedApplication].delegate;
BasicPhone* basicPhone = delegate.phone;
if (!basicPhone.connection || basicPhone.connection.state == TCConnectionStateDisconnected)
{
NSString* strToNumber = self.textOutgoingDest.text;
if (strToNumber && ![strToNumber isEqualToString:#""]) {
switch (_eOutgoingType) {
case BPOutgoingNumber:
break;
case BPOutgoingClient:
strToNumber = [NSString stringWithFormat:#"client:%#", strToNumber];
break;
default:
break;
}
NSDictionary* dictParams = [NSDictionary dictionaryWithObjectsAndKeys:strToNumber, #"To", nil];
[self.phone connectWithParams:dictParams];
}
else {
[self.phone connectWithParams:nil];
}
}
else
{
[basicPhone disconnect];
}
[self syncMainButton];
}
I have solved my issue
-(IBAction)mainButtonPressed:(id)sender
{
BasicPhoneAppDelegate* delegate = (BasicPhoneAppDelegate*)[UIApplication sharedApplication].delegate;
BasicPhone* basicPhone = delegate.phone;
if (!basicPhone.connection || basicPhone.connection.state == TCConnectionStateDisconnected)
{
NSString* strToNumber = self.textOutgoingDest.text;
if (strToNumber && ![strToNumber isEqualToString:#""])
{
strToNumber = [NSString stringWithFormat:#"%#", strToNumber];
NSDictionary* dictParams = [NSDictionary dictionaryWithObjectsAndKeys:strToNumber, #"number", nil];
[self.phone connectWithParams:dictParams];
}
else
{
[self.phone connectWithParams:nil];
}
}
else
{
[basicPhone disconnect];
}
[self syncMainButton];
}
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
I implemented “swipe to delete cell in TableView” and it works fine in iOS 7 but that same code is not working for iOS 8. Is there any changes done for iOS 8 in this?
After swiping the cell I see nothing in my “Groups” section in iOS 8 while in iOS 7 I see a delete button.
Here is the code I am using:
- (void)swipeableTableViewCell:(SWTableViewCell *)cell scrollingToState: (SWCellState)state
{
switch (state) {
case 0:
NSLog(#"utility buttons closed");
[customDropDown hideDropDown:dropDownFrame];
[customDropDown removeFromSuperview];
customDropDown = nil;
break;
case 1:
NSLog(#"left utility buttons open");
break;
case 2:
NSLog(#"right utility buttons open");
break;
default:
break;
}
}
- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{
switch (index)
{
case 0:
{
if (cell.rightUtilityButtons.count == 1)
{
NSArray * arr = [[NSArray alloc] init];
arr = [NSArray arrayWithArray:[self.groupsInfoDict allKeys]];
if(customDropDown == nil)
{
indexPathForSelectedcontact = [self.groupListTableView indexPathForCell:cell];
CGRect frame = [self.groupListTableView rectForRowAtIndexPath:indexPathForSelectedcontact];
CGRect animatedViewFrame = [self.view convertRect:frame fromView:self.groupListTableView];
CGFloat height = self.view.frame.size.height-(animatedViewFrame.origin.y+44);
NSString* direction;
if (height<88)
{
direction = #"up";
CGFloat noOfRowHeight = [arr count]*40;
if (noOfRowHeight <animatedViewFrame.origin.y)
{
height = noOfRowHeight;
}
else
{
height = animatedViewFrame.origin.y;
}
}
else
{
direction = #"down";
CGFloat noOfRowHeight = [arr count]*40;
if (noOfRowHeight <height)
{
height = noOfRowHeight;
}
}
dropDownFrame = CGRectMake(animatedViewFrame.origin.x, animatedViewFrame.origin.y, 160,height);
customDropDown = [[CustomDropDown alloc]showDropDown:dropDownFrame arrayOfData:arr ArrayOfimages:nil inDirection:direction onView:self.view];
customDropDown.delegate = self;
}
else
{
[customDropDown hideDropDown:dropDownFrame];
[customDropDown removeFromSuperview];
dropDownFrame = CGRectZero;
customDropDown = nil;
}
}
else
{
NSIndexPath* indexpath = [self.groupListTableView indexPathForCell:cell];
NSArray* arrayOfKeys = (NSArray *)self.groupsInfoDict.allKeys;
NSArray *sortedValues = [arrayOfKeys sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
groupTitleSelectedForRename = [sortedValues objectAtIndex:indexpath.row];
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:#"Events" bundle:nil];
AddANewGroupViewController *addANewGroupViewController = [storyboard instantiateViewControllerWithIdentifier:#"AddANewGroupViewController"];
addANewGroupViewController.screenType = kScreenEditGroup;
addANewGroupViewController.useTableIndex = YES;
addANewGroupViewController.allowSearchControl = YES;
addANewGroupViewController.groupTitleSelectedForRename = groupTitleSelectedForRename;
[self.navigationController pushViewController:addANewGroupViewController animated:YES];
//[self getGroupNameAlert:groupTitleSelectedForRename ifAlreadyExists:NO];
}
break;
}
case 1:
{
NSIndexPath* indexPath = [self.groupListTableView indexPathForCell:cell];
// Change the cell appearance
NSArray* arrayOfKeys = (NSArray *)self.groupsInfoDict.allKeys;
NSArray *sortedValues = [arrayOfKeys sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
selectedGroupKey = [sortedValues objectAtIndex:indexPath.row];
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Are you sure you want to delete this group?" delegate:self cancelButtonTitle:#"NO" otherButtonTitles:#"YES", nil];
[alert setTag:990];
[alert show];
break;
}
default:
break;
}
}
- (BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell
{
// allow just one cell's utility button to be open at once
return YES;
}
- (BOOL)swipeableTableViewCell:(SWTableViewCell *)cell canSwipeToState:(SWCellState)state{
switch (state) {
case 1:
// set to NO to disable all left utility buttons appearing
return YES;
break;
case 2:
// set to NO to disable all right utility buttons appearing
return YES;
break;
default:
break;
}
return YES;
}
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
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));
}
})}