I have inherited a old iOS project that was created back in 2012 and is using some really old school techniques. I converted from 32 bit to 64 bit.
On the settings screens, the height of the settings items are not tall enough, causing the settings pages to look jumbled.
Any idea what is making this happen?
This page has no xib file, it's generated in code.
#import "GeneralSettings.h"
//preference keys
#define kGENERAL_ACCOUNT #"general_account"
#define kGENERAL_EXPAND_RESULTS #"general_expand_results"
#define kGENERAL_FINALS_ONLY #"general_finals_only"
#define kGENERAL_SEARCH_DAYS #"general_search_days"
#define kGENERAL_STARTUP #"general_startup"
#interface GeneralSettings ()
#end
#implementation GeneralSettings
+ (NSString *)accountNumber {
return [[NSUserDefaults standardUserDefaults]
objectForKey:kGENERAL_ACCOUNT];
}
+ (BOOL)expandResults {
NSString *expandResults = [[NSUserDefaults standardUserDefaults]
objectForKey:kGENERAL_EXPAND_RESULTS];
return expandResults ? [expandResults boolValue] : YES;
}
+ (BOOL)finalsOnly {
return [[NSUserDefaults standardUserDefaults]
boolForKey:kGENERAL_FINALS_ONLY];
}
+ (NSInteger)numberOfDays {
NSString *numberOfDays = [[NSUserDefaults standardUserDefaults]
objectForKey:kGENERAL_SEARCH_DAYS];
if (numberOfDays) {
if (([numberOfDays integerValue] != 90) || [Globals
sharedInstance].isQA) {
return [numberOfDays integerValue];
}
//value of 90 lingering from QA session, reset to 15
[[NSUserDefaults standardUserDefaults] setValue:#"15"
forKey:kGENERAL_SEARCH_DAYS];
return 15;
}
//default value
return 7;
}
+ (NSInteger)showAtStartup {
return [[NSUserDefaults standardUserDefaults]
integerForKey:kGENERAL_STARTUP];
}
+ (void)setAccountNumber:(NSString *)accountNumber {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setValue:accountNumber forKey:kGENERAL_ACCOUNT];
[prefs synchronize];
}
+ (void)convert {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if ([prefs objectForKey:#"finalsOnly"]) {
BOOL value = [prefs boolForKey:#"finalsOnly"];
[prefs removeObjectForKey:#"finalsOnly"];
[prefs setBool:value forKey:kGENERAL_FINALS_ONLY];
[prefs synchronize];
}
if ([prefs objectForKey:#"searchDays"]) {
NSString *value = [prefs objectForKey:#"searchDays"];
int index = 2;
if ([value isEqualToString:#"1 Days"]) {
index = 0;
}
else if ([value isEqualToString:#"3 Days"]) {
index = 1;
}
else if ([value isEqualToString:#"15 Days"]) {
index = 3;
}
[prefs removeObjectForKey:#"searchDays"];
[prefs setInteger:index forKey:kGENERAL_SEARCH_DAYS];
[prefs synchronize];
}
if ([prefs objectForKey:#"showAtStartup"]) {
NSString *value = [prefs objectForKey:#"showAtStartup"];
int index = 0;
if ([value isEqualToString:#"Contacts"]) {
index = 1;
}
else if ([value isEqualToString:#"Lookup Test"]) {
index = 2;
}
[prefs removeObjectForKey:#"showAtStartup"];
[prefs setInteger:index forKey:kGENERAL_STARTUP];
[prefs synchronize];
}
}
- (id)init {
self = [super initWithTitle:xGeneralSettings withIconName:#"icon-
settings-general.png"];
if (self) {
//initialization
Globals *globals = [Globals sharedInstance];
SettingsSection *section = [self.sections objectAtIndex:0];
//add account settings section
SettingsSection *accountSection = [[[SettingsSection alloc]
initWithTitle:xAccountSettings] autorelease];
[self.sections addObject:accountSection];
//create settings
Setting *startupSetting = [[[Setting alloc]
initWithKey:kGENERAL_STARTUP withTitle:xGeneralStartupTitle
withType:pickerSetting] autorelease];
SearchDaysSetting *searchDaysSetting = [[[SearchDaysSetting alloc]
initWithKey:kGENERAL_SEARCH_DAYS withTitle:xGeneralSearchDaysTitle
withType:pickerSetting] autorelease];
Setting *finalsSetting = [[[Setting alloc]
initWithKey:kGENERAL_FINALS_ONLY withTitle:xGeneralFinalsOnlyTitle
withType:toggleSetting] autorelease];
Setting *expandSetting = [[[Setting alloc]
initWithKey:kGENERAL_EXPAND_RESULTS
withTitle:xGeneralExpandResultsTitle withType:toggleSetting] autorelease];
AccountSetting *accountSetting = [[[AccountSetting alloc]
initWithKey:kGENERAL_ACCOUNT withTitle:xGeneralAccountTitle
withType:pickerSetting] autorelease];
//set setting parameters
[startupSetting setPickerValuesFromString:xGeneralStartupValues
withDefaultValue:0];
[searchDaysSetting
setPickerValuesFromString:xGeneralSearchDaysValues withDefaultValue:2];
[finalsSetting setToggle:NO
withSummary:xGeneralFinalsOnlySummary];
[expandSetting setToggle:YES
withSummary:xGeneralExpandResultsSummary];
[accountSetting setPickerValues:[globals allAccounts]
withDefaultValue:[globals defaultAccount]];
if ([Globals sharedInstance].isQA) {
[searchDaysSetting.pickerValues addObject:#"90 Days"];
}
//add settings to sections
[section.settings addObject:startupSetting];
[section.settings addObject:searchDaysSetting];
[section.settings addObject:finalsSetting];
[section.settings addObject:expandSetting];
[accountSection.settings addObject:accountSetting];
}
return self;
}
#end
#pragma mark - AccountSetting class
#implementation AccountSetting
- (NSInteger)intValue {
NSArray *picklist = self.pickerValues;
NSString *value = [self stringValue];
//return the index of our value
for (int i = 0; i < picklist.count; i++) {
if ([[picklist objectAtIndex:i] isEqualToString:value]) {
return i;
}
}
return [super intValue];
}
- (void)setInteger:(NSInteger)index shouldSave:(BOOL)saveValue {
NSArray *picklist = self.pickerValues;
if ((index > -1) && (index < picklist.count)) {
//save the value determined by this index
[self setString:[picklist objectAtIndex:index]
shouldSave:saveValue];
}
}
#end
#pragma mark - AccountSetting class
#implementation SearchDaysSetting
- (NSInteger)intValue {
//return the index of our value
switch ([super intValue]) {
case 1:
return 0;
case 3:
return 1;
case 7:
return 2;
case 15:
return 3;
case 90:
return [self pickerValues].count - 1; //safe return of assumed index, which might not exist
}
return [[self defaultValue] integerValue];
}
- (void)setInteger:(NSInteger)index shouldSave:(BOOL)saveValue {
NSInteger numberOfDays = 7;
//save the value determined by this index
switch (index) {
case 0:
numberOfDays = 1;
break;
case 1:
numberOfDays = 3;
break;
case 2:
numberOfDays = 7;
break;
case 3:
numberOfDays = 15;
break;
case 4:
numberOfDays = 90;
break;
}
[super setInteger:numberOfDays shouldSave:saveValue];
}
#end
Try to look for UITableViewDataSource method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 46;//here is height of cell
}
Or, add the following in viewDidLoad:
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 46;//here is height of cell
I have this array with strings and I want to randomize it and display the output in a label. But with this code I'm having always the same strange output which is "2"...Any ideas what I'm doing wrong?
- (void)viewDidLoad {
[super viewDidLoad];
self.quoteInput.delegate=self;
self.quoteLabel=_quotationLabel;
self.correctLabel.alpha=0;
self.wrongLabel.alpha=0;
_quoteInput.delegate=self;
_levelOne = #[
[words Quotes:#"First Quote."],
[words Quotes:#"Second Quote."],
[words Quotes:#"And so on."]];
}
-(void)randomQuotes{
for (NSInteger x = 0; x < [_levelOne count]; x++) {
NSInteger randInt = arc4random() % ([_levelOne count] - x) + x;
[_levelOne objectAtIndex:randInt];
NSString *one = [NSString stringWithFormat:#"%d", randInt];
self.quoteLabel.text = one;
}
}
- (IBAction)generateQuote:(UIButton *)sender {
[self randomQuotes];
}
EDIT
The words class:
+ (instancetype)Quotes:(NSString *)quotes
{
return [[words alloc] initWithQuotes:quotes];
}
Unless you can explain what [word Quotes:] method does, it should be much simpler than what you are trying to do.
_levelOne = #[#"First Quote.", "Second Quote.", #"And so on."];
-(void) randomQuotes{
NSInteger randInt = arc4random_uniform( [_levelOne count] );
self.quoteLabel.text = [_levelOne objectAtIndex:randInt];
}
So, I have a UIPicker view which gets populated from a NSMutableArray as long as the input is not "NULL".
So my picker shows all the values except NULL.
Now, I have a UITextField box and a button. So whatever I type in the text field, and I click the button, if it matches to anything which was there in the NSMutableArray ( which was used to populate UIPickerView ), it sets it to NULL and refreshes the UIPicker so that it doesn't get displayed anymore.
For some reason, I'm able to set the value to NULL(checked using NSLog), but the picker never gets updates, and neither does the NSMutable Array.
-(void) loadthepicker
{
NSMutableArray *getarray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"FilerNamesArray"]];
pickerLoaderArray=[[NSMutableArray alloc] init];
for (int j=0; j<20; j++) {
if ([[getarray objectAtIndex:j] isEqualToString:#"NULL"])
{
// do nothing..don't load
}
else // add that filter to pickerLoaderArray
{
[pickerLoaderArray addObject:[getarray objectAtIndex:j]];
}
} // end of for
[pickerView reloadAllComponents];
[pickerView selectRow:0 inComponent:0 animated:NO];
}
-(NSInteger)numberOfComponentsInPickerView:(NSInteger)component
{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)picker numberOfRowsInComponent:(NSInteger)component
{
return [pickerLoaderArray count];
}
-(NSString *)pickerView:(UIPickerView *)picker titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [pickerLoaderArray objectAtIndex:row];
}
The button:
- (IBAction)deleteButton:(id)sender {
NSUserDefaults *CheckFiltersUsed = [NSUserDefaults standardUserDefaults];
NSInteger myInt = [CheckFiltersUsed integerForKey:#"FiltersUsed"];
if (myInt<=20 && myInt>0) {
NSLog(#"number of filters used before deleting %ld",(long)myInt);
[CheckFiltersUsed setInteger:myInt-1 forKey:#"FiltersUsed"];
[CheckFiltersUsed synchronize];
// get names array
NSMutableArray *getarray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"FilerNamesArray"]];
NSArray *get=getarray;
// at location where name matches with selectedfilter..put NULL
for (int j=0; j<20; j++) {
if ( [[getarray objectAtIndex:j] isEqualToString:_filterToDelete.text] && isFilterDeleted==NO )
{
NSLog(#"------currently %d is %#",j,[getarray objectAtIndex:j]);
[getarray insertObject:#"NULL" atIndex:j];
NSLog(#"------now %d is %#",j,[getarray objectAtIndex:j]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"" message: #"Deleted" delegate: nil cancelButtonTitle:#"Ok" otherButtonTitles:nil]; [alert show];
isFilterDeleted=YES;
[[NSUserDefaults standardUserDefaults] setObject:getarray forKey:#"FilerNamesArray"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self loadthepicker];
}
else
{
NSLog(#"No matching filter name");
}
} // end of for
//now save this array back.
}
else
{
NSUserDefaults *CheckFiltersUsed = [NSUserDefaults standardUserDefaults];
NSInteger myInt = [CheckFiltersUsed integerForKey:#"FiltersUsed"];
NSLog(#"Wrong number of filters!!!... %d",myInt);
}
}
If i get what you are trying to do, you want to delete the equal string from the array and the picker as well. But instead of that you just insert another NSString object into index 'j'
In the deleteButton method:
Instead of this line
[getarray insertObject:#"NULL" atIndex:j];
Call
[getarray removeObjectAtIndex:j];
**Update
In the loadPicker just remove the if statment to check if the string is equal to #"NULL"
So instead of:
for (int j=0; j<20; j++) {
if ([[getarray objectAtIndex:j] isEqualToString:#"NULL"])
{
// do nothing..don't load
}
else // add that filter to pickerLoaderArray
{
[pickerLoaderArray addObject:[getarray objectAtIndex:j]];
}
}
Do:
for(NSString *pickerValue in getarray){
[pickerLoaderArray addObject:pickerValue];
}
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));
}
})}
I want load my picker by a for loop.From 1 to 999.I loaded manually.
My code is here.How I use a "for loop" for load automaticaly. Thanks
- (void)numberWasSelected:(NSNumber *)selectedIndex element:(id)element;
#synthesize numbers = _numbers;
#synthesize selectedIndex = _selectedIndex;
self.numbers = [NSArray arrayWithObjects:#"1", #"2", #"3",............#"999" nil];
- (IBAction)selectNumbers:(UIControl *)sender {
[ActionSheetStringPicker showPickerWithTitle:#"Select a number !" rows:self.numbers
initialSelection:self.selectedIndex target:self
successAction:#selector(numberWasSelected:element:)
cancelAction:#selector(actionPickerCancelled:) origin:sender];
}
- (void)numberWasSelected:(NSNumber *)selectedIndex element:(id)element {
self.selectedIndex = [selectedIndex intValue];
self.numberTextField.text = [self.numbers objectAtIndex:self.selectedIndex];
}
NSMutableArray* array = [NSMutableArray new];
for (int i = 1; i <= 999; i++) {
[array addObject:[NSString stringWithFormat:#"%d", i]];
}
self.numbers = array;