iOS settings page items are jumbled - ios

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

Related

How to solve it ( EXC_BAD_ADDRESS in Objective-C )?

sometimes, fatal error occurs in my app with EXC_BAD_ADDRESS error log.
What is the cause of my code?
crash log
0. Crashed: GGMutableDictionary Isolation Queue
0 libobjc.A.dylib 0x184e2c150 objc_msgSend + 16
1 CoreFoundation 0x1862e0d04 -[NSDictionary descriptionWithLocale:indent:] + 916
2 CoreFoundation 0x1862e0dac -[NSDictionary descriptionWithLocale:indent:] + 1084
3 Foundation 0x186da35a4 _NSDescriptionWithLocaleFunc + 76
4 CoreFoundation 0x1863788bc __CFStringAppendFormatCore + 8440
5 CoreFoundation 0x18637678c _CFStringCreateWithFormatAndArgumentsAux2 + 244
6 Foundation 0x186da3418 +[NSString stringWithFormat:] + 68
7 app 0x10019f4b8 -[TinyDB saveAsync] + 4296963256
8 app 0x10019c86c __26-[TinyDB putString:value:]_block_invoke + 4296951916
9 libdispatch.dylib 0x18526e9a0 _dispatch_client_callout + 16
10 libdispatch.dylib 0x18527bee0 _dispatch_barrier_sync_f_invoke + 84
11 app 0x10019c7e0 -[TinyDB putString:value:] + 4296951776
source file
This class is used asynchronously from many other class.
This class should have thread safe. But EXC_BAD_ADDRESS fatal error occurs in saveAsync method.
I think weakDictionaryRef or isolationQueue variables are deallocated. I want to fix this problem. What should I fix in this code?
Thank you for your advice.
TinyDB.h file
#interface TinyDB : NSObject
#property (nonatomic, retain) NSString * docPath;
// #property (nonatomic, retain) NSMutableDictionary * dictionary;
#property (nonatomic, retain) NSFileManager * fileManager;
#property (nonatomic, retain) NSString * dir;
#property (nonatomic, assign) BOOL flagWrite;
- (instancetype)initWithFile:(NSString *)file;
- (NSString *)getDocPath;
- (void)putDouble:(NSString *)key value:(double)value;
- (void)putInt:(NSString *)key value:(NSInteger)value;
- (void)putMutableArray:(NSString *)key value:(NSMutableArray *)value;
- (void)putString:(NSString *)key value:(NSString *)value;
- (void)putTinyDB:(NSString *)key value:(TinyDB *)value;
- (void)putLong:(NSString *)key value:(NSInteger)value;
- (void)putBool:(NSString *)key value:(BOOL)value;
- (void)putDictionary:(NSString *)key value:(NSDictionary *)value;
- (id)get:(NSString *)key;
- (NSMutableArray *)getMutableArray:(NSString *)key;
- (BOOL)has:(NSString *)key;
- (void)saveAsync;
- (void)save;
- (NSString *)jsonString;
- (NSString *)stringify:(id)obj;
- (NSString *)getSet:(id)value;
- (NSString *)getPairSet:(NSString *)key value:(id)value;
- (NSMutableDictionary*)getMutableDictionary:(NSString*)key;
- (NSString *)getString:(NSString *)key;
- (BOOL)getBool:(NSString*)key;
- (NSArray *)allKeys;
- (void)removeObjectForKey:(NSString*)key;
#end
TinyDB.m file
#implementation TinyDB
{
#private dispatch_queue_t isolationQueue_;
#private __strong NSMutableDictionary * _myDictionary;
}
#synthesize docPath=docPath,fileManager=fileManager,dir=dir,flagWrite=flagWrite;
BOOL flagOnSave = false;
BOOL flagWrite = true;
NSString* dir;
NSString* docPath = #"";
NSLock* _dicLock=nil;
NSFileManager* fileManager;
__weak id _weakDictionaryRef;
-(id)initWithFile:(NSString *)file{
self = [super init];
docPath = file;
// ##########################################
isolationQueue_ = dispatch_queue_create([#"GGMutableDictionary Isolation Queue" UTF8String], DISPATCH_QUEUE_CONCURRENT);
// ##########################################
fileManager = [NSFileManager defaultManager];
dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) firstObject];
dir = [NSString stringWithFormat:#"%#/myapp/",dir];
BOOL flagFileExist = [fileManager fileExistsAtPath:[[NSString alloc] initWithFormat:#"%#/%#.myapp",dir,docPath]];
_myDictionary = [[NSMutableDictionary alloc] init];
if(flagFileExist){
[BSDebugger log:[NSString stringWithFormat:#"DEBUG_myapp_CONFIG : File Found!!! %# --> ",file]];
#try{
NSMutableDictionary* dic = [[NSMutableDictionary alloc] initWithContentsOfFile:[[NSString alloc] initWithFormat:#"%#/%#.myapp",dir,docPath]];
_myDictionary = [[NSMutableDictionary alloc] initWithDictionary:dic];
}#catch(NSException * e){
_myDictionary = [[NSMutableDictionary alloc] init];
}#finally{
}
}else{
[BSDebugger log:[NSString stringWithFormat:#"DEBUG_myapp_CONFIG : File Not Found!!!--> %# ",file]];
_myDictionary = [[NSMutableDictionary alloc] init];
}
_weakDictionaryRef = _myDictionary;
[self saveAsync];
return self;
}
-(void)putString:(NSString*)key value:(NSString*)value{
dispatch_barrier_sync(isolationQueue_, ^{
if(value == nil){
return;
}
#try{
[_myDictionary setObject:value forKey:key];
}#catch(NSException* e){
NSMutableDictionary* buff = [[NSMutableDictionary alloc] initWithDictionary:_myDictionary];
_myDictionary = buff;
_weakDictionaryRef = _myDictionary;
dispatch_barrier_sync(isolationQueue_, ^{
[_myDictionary setObject:value forKey:key];
});
}#finally{
}
[self saveAsync];
});
}
- (void)putDouble:(NSString *)key value:(double)value{
dispatch_barrier_sync(isolationQueue_, ^{
[_myDictionary setObject:[[NSNumber alloc] initWithDouble:value] forKey:key];
[self saveAsync];
});
}
- (void)putInt:(NSString *)key value:(NSInteger)value{
dispatch_barrier_sync(isolationQueue_, ^{
#try{
[_myDictionary setObject:[[NSNumber alloc] initWithInteger:value] forKey:key];
}#catch(NSException* e){
NSMutableDictionary* buff = [[NSMutableDictionary alloc] initWithDictionary:_myDictionary];
_myDictionary = buff;
_weakDictionaryRef = _myDictionary;
[_myDictionary setObject:[[NSNumber alloc] initWithInteger:value] forKey:key];
}#finally{
}
[self saveAsync];
});
}
- (void)putMutableArray:(NSString *)key value:(NSMutableArray *)value{
dispatch_barrier_sync(isolationQueue_, ^{
if( key != nil && value != nil ){
[_myDictionary setObject:value forKey:key];
[self saveAsync];
}
});
}
- (void)putTinyDB:(NSString *)key value:(TinyDB *)value{
dispatch_barrier_sync(isolationQueue_, ^{
TinyDB* db = value;
NSString* docuPath = [db getDocPath];
#try{
[_myDictionary setObject:docuPath forKey:key];
}#catch(NSException* e){
NSMutableDictionary* buff = [[NSMutableDictionary alloc] initWithDictionary:_myDictionary];
_myDictionary = buff;
_weakDictionaryRef = _myDictionary;
dispatch_barrier_sync(isolationQueue_, ^{
[_myDictionary setObject:docuPath forKey:key];
});
}#finally{
}
[self saveAsync];
});
}
- (void)putLong:(NSString *)key value:(NSInteger)value{
dispatch_barrier_sync(isolationQueue_, ^{
[_myDictionary setObject:[[NSNumber alloc] initWithInteger:value] forKey:key];
[self saveAsync];
});
}
- (void)putBool:(NSString *)key value:(BOOL)value{
dispatch_barrier_sync(isolationQueue_, ^{
[_myDictionary setObject:[[NSNumber alloc] initWithBool:value] forKey:key];
[self saveAsync];
});
}
- (void)putDictionary:(NSString *)key value:(NSDictionary *)value{
dispatch_barrier_sync(isolationQueue_, ^{
[_myDictionary setObject:value forKey:key];
[self saveAsync];
});
}
-(void)removeObjectForKey:(NSString*)key{
dispatch_barrier_sync(isolationQueue_, ^{
if( _myDictionary != nil && [_myDictionary objectForKey:key] != nil ){
[_myDictionary removeObjectForKey:key];
}
});
}
-(void) save{
dispatch_barrier_sync(isolationQueue_, ^{
#try {
// NSLog([NSString stringWithFormat:#"writeToFile Error : orgPath = %#/%#.myapp / %#",dir,docPath, self.dictionary ]);
// NSMutableDictionary* nsDic = self.dictionary;
if( _myDictionary != nil ){
NSDictionary * _dictionary =
(__bridge NSDictionary *)(CFPropertyListCreateDeepCopy(kCFAllocatorDefault,
(__bridge CFPropertyListRef)(_myDictionary),
kCFPropertyListImmutable));
if( _dictionary != nil ){
[_dictionary writeToFile:[[NSString alloc] initWithFormat:#"%#/%#.myapp",dir,docPath] atomically: false];
}
}
}#catch (NSException *exception) {
_myDictionary = [[NSMutableDictionary alloc] initWithDictionary:_myDictionary];
_weakDictionaryRef = _myDictionary;
}#finally {
}
});
}
// ################################################################
// normal function
- (NSString *)jsonString{
__block NSString* buff = #"";
dispatch_barrier_sync(isolationQueue_, ^{
if( _myDictionary != nil ){
NSDictionary * _dictionary = nil;
// dispatch_barrier_sync(isolationQueue_, ^{
_dictionary = (__bridge NSDictionary *)(CFPropertyListCreateDeepCopy(kCFAllocatorDefault,
(__bridge CFPropertyListRef)(_myDictionary),
kCFPropertyListImmutable));
if( _dictionary != nil ){
buff = [self stringify:_dictionary];
}
}else{
NSLog(#"buff = [self stringify:_myDictionary]; is nil ");
}
});
return buff;
}
- (NSString *)stringify:(id)obj{
if([obj isKindOfClass:[NSDictionary class]]){
int idx = 0;
NSString* buff = #"{";
if( obj != nil ){
NSDictionary* dic = [NSDictionary dictionaryWithDictionary:obj]; //obj;
for(NSString* key in dic){
id value = [dic objectForKey:key];
if(idx != 0){
buff = [[NSString alloc] initWithFormat:#"%#%#",buff,#","];
}
buff = [[NSString alloc] initWithFormat:#"%#%#",buff,[self getPairSet:key value:value]];
idx++;
}
}
buff = [[NSString alloc] initWithFormat:#"%#%#",buff,#"}"];
return buff;
}else if([obj isKindOfClass:[NSArray class]]){
int idx = 0;
NSString* buff = #"[";
if( obj != nil ){
NSMutableArray* _a = [[NSMutableArray alloc] init];
for( int ai = 0; ai < [obj count]; ai++){
if( [obj objectAtIndex:ai] != nil ){
[_a addObject:[obj objectAtIndex:ai]];
}
}
NSArray* arr = [NSArray arrayWithArray:_a]; //obj;
for(id value in arr){
if(idx != 0){
buff = [[NSString alloc] initWithFormat:#"%#%#",buff,#","];
}
buff = [[NSString alloc] initWithFormat:#"%#%#",buff,[self getSet:value]];
idx++;
}
}
buff = [[NSString alloc] initWithFormat:#"%#%#",buff,#"]"];
return buff;
}else{
return [self getSet:obj];
}
}
- (NSString *)getSet:(id)value{
NSString* buff = #"";
if([value isKindOfClass:[NSString class]]){
buff = [[NSString alloc] initWithFormat:#"%#\"%#\"",buff,value];
}else if([value isKindOfClass:[NSNumber class]]){
NSNumber* val = value;
buff = [[NSString alloc] initWithFormat:#"%#%#",buff,[val stringValue]];
}else{
buff = [[NSString alloc] initWithFormat:#"%#%#",buff,[self stringify:value]];
}
return buff;
}
- (NSString *)getPairSet:(NSString *)key value:(id)value{
NSString* buff = #"";
if([value isKindOfClass:[NSString class]]){
buff = [[NSString alloc] initWithFormat:#"%#\"%#\":\"%#\"",buff,key,value];
}else if([value isKindOfClass:[NSNumber class]]){
buff = [[NSString alloc] initWithFormat:#"%#\"%#\":%#",buff,key,[value stringValue]];
}else{
buff = [[NSString alloc] initWithFormat:#"%#\"%#\":%#",buff,key,[self stringify:value]];
}
return buff;
}
-(NSMutableDictionary*)getMutableDictionary:(NSString*)key{
NSMutableDictionary* dic = [[NSMutableDictionary alloc] init];
id obj = [_myDictionary objectForKey:key];
if(obj != nil){
dic = [[NSMutableDictionary alloc] initWithDictionary:obj];
}
return dic;
}
-(NSArray *)allKeys{
__block NSArray* arr = nil;
dispatch_barrier_sync(isolationQueue_, ^{
if( _myDictionary != nil ){
arr = [_myDictionary allKeys];
}
});
return arr;
}
- (NSString *)getDocPath{
return docPath;
}
- (id)get:(NSString *)key{
__block id _obj = nil;
dispatch_barrier_sync(isolationQueue_, ^{
_obj = [_myDictionary objectForKey:key];
});
return _obj;
}
- (NSString *)getString:(NSString *)key{
__block NSString* returnStr = #"";
dispatch_barrier_sync(isolationQueue_, ^{
if([_myDictionary objectForKey:key]==nil){
returnStr = #"";
}
if([[_myDictionary objectForKey:key] isKindOfClass:[NSString class]]){
returnStr = [_myDictionary objectForKey:key];
}else{
returnStr = #"";
}
});
return returnStr;
}
- (BOOL)getBool:(NSString*)key{
__block BOOL flag = false;
dispatch_barrier_sync(isolationQueue_, ^{
if([_myDictionary objectForKey:key]==nil){
flag = NO;
}
if([[_myDictionary objectForKey:key] isKindOfClass:[NSNumber class]]){
NSNumber* boolValue = [_myDictionary objectForKey:key];
if([boolValue boolValue] == YES){
flag = YES;
}else{
flag = NO;
}
}else{
flag = NO;
}
});
return flag;
}
- (NSMutableArray *)getMutableArray:(NSString *)key{
__block NSMutableArray* _arr = nil;
dispatch_barrier_sync(isolationQueue_, ^{
_arr = [_myDictionary objectForKey:key];
});
return _arr;
}
- (BOOL)has:(NSString *)key{
__block BOOL flag = false;
dispatch_barrier_sync(isolationQueue_, ^{
if([_myDictionary objectForKey:key] != nil){
flag = true;
}else{
flag = false;
}
});
return flag;
}
// #########################
// save function
int flagTest = 0;
bool mark = 0;
NSTimer* saveTimer = nil;
-(void)saveAsync{
#try {
[BSDebugger log:[NSString stringWithFormat:#"_weakDictionaryRef : %# ",_weakDictionaryRef ]];
if( _myDictionary != nil ){
if( _weakDictionaryRef != nil ){
NSDictionary * _dictionary = nil;
_dictionary = (__bridge NSDictionary *)(CFPropertyListCreateDeepCopy(kCFAllocatorDefault,
(__bridge CFPropertyListRef)(_myDictionary),
kCFPropertyListImmutable));
#try{
flagOnSave = true;
UIBackgroundTaskIdentifier taskID = [myappCore beginBackgroundUpdateTask];
flagWrite = false;
NSString* orgPath = [[NSString alloc] initWithFormat:#"%#/%#.myapp",dir,docPath ];
#try {
if( _dictionary != nil ){
[_dictionary writeToFile:orgPath atomically:YES];
}
}#catch (NSException *exception) {
[BSDebugger log:[NSString stringWithFormat:#"DEBUG_myapp_TINYDB : %#",[exception callStackSymbols]]];
}#finally {
}
flagWrite = true;
flagOnSave = false;
[myappCore endBackgroundUpdateTask:taskID];
}#catch (NSException *exceptionMain) {
[BSDebugger log:[NSString stringWithFormat:#"DEBUG_myapp_TINYDB : %#",[exceptionMain callStackSymbols]]];
}#finally {
_dictionary = nil;
}
return;
// });
}
}
}#catch (NSException *exception) {
}#finally {
// [_dicLock unlock];
}
}
#end
Some ideas:
Turn on zombies (How to enable NSZombie in Xcode). You'll get more information about the object causing the crash when you do that.
If you can make the error happen at will, set a breakpoint at the top of saveAsync and step through it.
Change the stringWithFormat calls somehow so they don't reference anything that might be deallocated and see if the problem goes away. If it does, you'll know what was causing it.
I find it sometimes helps to override retain and release in objects I'm suspicious of and either print something out or set a breakpoint so I can see who might be over-releasing an object.

Issue with setting picker view content

In my app a user can change the number of picker view elements by clicking some buttons. Everything is ok with that. But after that I want to show a word in it but the picker view is probably not ready and the app just crashes. Here is the cod for that
- (IBAction)changeNumberOfLettersToShow:(id)sender {
int numberOfLetters = (int)((UIBarButtonItem *)sender).tag;
switch (numberOfLetters) {
case 0:
[self setNumberOfLetters:[NSNumber numberWithInt: 10] andLanguage:nil];
break;
default:
[self setNumberOfLetters:[NSNumber numberWithInt: numberOfLetters] andLanguage:nil];
break;
}
[self showTheFirstWordForNumberOfLetters:numberOfLetters];
}
- (void) showTheFirstWordForNumberOfLetters: (int) numberOfLetters{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:numberOfLetters], [NSNumber numberWithInt:0], nil] forKey:#"currentPositon"];
NSArray *words = [allWordsForCurrentLanguage objectForKey:[NSString stringWithFormat:#"%#%d",[[NSUserDefaults standardUserDefaults] objectForKey:#"language"], numberOfLetters]];
[self displayWord:[[words objectAtIndex:0] uppercaseString] animated:YES];
}
- (void) setNumberOfLetters:(NSNumber *)numberOfLetters andLanguage: (NSString *) language {
[pickerHelper setNumberOfLettersToShow:numberOfLetters andLanguage:nil];
[self.picker reloadAllComponents];
}
- (void) displayWord:(NSString *)word animated:(BOOL)animated {
pickerHelper.pickerWorkingAutomatically = YES;
for (NSUInteger i = 0; i < [word length]; i++) {
NSString *letter = [NSString stringWithFormat:#"%c", [word characterAtIndex:i]];
[self displayLetter:letter
atComponent:i
animated:animated];
}
pickerHelper.pickerWorkingAutomatically = NO;
}
The picker looks similar to the one on the picture:
http://sourcefreeze.com/wp-content/uploads/2015/03/uipickerview-multi-selected-row.png
So I actually want to make a word from the fragments of a picker containing letters (which also user to work fine before I started doing it) and it actually works on a simulator.
UPDATED:
- (void) displayLetter:(NSString *)letter atComponent:(NSUInteger)component animated:(BOOL)animated {
NSUInteger row;
if (animated){
NSUInteger selectedRow = [self.picker selectedRowInComponent:component];
row = selectedRow + ([self.alphabet count] - selectedRow % [self.alphabet count]) + [self.alphabet indexOfObject:letter];
}
else
row = ((UINT16_MAX) / (2 * [self.alphabet count]) * [self.alphabet count]) + [self.alphabet indexOfObject:letter];
[self.picker selectRow:row
inComponent:component
animated:animated];
}

Display image based on random string from array

I have a list of strings in two arrays truth & dare that are loaded from a plist then randomised and displayed to the user in a label these could be truth or dares. I would like to display a image for both truth and dare when each one is displayed dependant on which array it is loaded from.
As i load the plist file into an array on load im not sure how to go about doing this? Im very new to xcode and am excited at the progress im making so far however.
This is the full code from my .m file
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#synthesize plistArray;
- (void)viewDidAppear:(BOOL)animated {
[self becomeFirstResponder];
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
NSString *path = [[NSBundle mainBundle] pathForResource:
#"data" ofType:#"plist"];
if ([[defaults objectForKey:#"truthonoff"] isEqualToString:#"YES"] && [[defaults objectForKey:#"dareonoff"] isEqualToString:#"YES"] ) {
self.text.text =#"Are you ready for this?";
NSDictionary *plistDict1 = [[NSDictionary alloc] initWithContentsOfFile:path];
NSArray * plistArray1 = plistDict1[#"truth"];
NSDictionary *plistDict2 = [[NSDictionary alloc] initWithContentsOfFile:path];
NSArray *plistArray2 = plistDict2[#"dare"];
self.plistArray = [[plistArray1 arrayByAddingObjectsFromArray:plistArray2] mutableCopy];
}
else if ([[defaults objectForKey:#"truthonoff"] isEqualToString:#"YES"] ) {
self.text.text =#"I hope you are feeling brave!";
NSDictionary *plistDict3 = [[NSDictionary alloc] initWithContentsOfFile:path];
NSArray *plistArray3 = plistDict3[#"truth"] ;
self.plistArray = [plistArray3 mutableCopy];
NSLog(#"%#", plistArray);
}
else if ([[defaults objectForKey:#"dareonoff"] isEqualToString:#"YES"] ) {
self.text.text =#"This could be interesting!";
NSDictionary *plistDict4 = [[NSDictionary alloc] initWithContentsOfFile:path];
NSMutableArray *plistArray4 = plistDict4[#"dare"];
self.plistArray = [plistArray4 mutableCopy];
NSLog(#"%#", plistArray);
}
else {
self.text.text =#"Please turn on Truth or Dare";
}
}
- (void)viewDidDisappear:(BOOL)animated {
[self becomeFirstResponder];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
// Do your thing after shaking device
if ([plistArray count] == 0) {
self.text.text = #"Please Upgrade for more";
}
else {
////display random quote from array
int randV = arc4random() % self.plistArray.count;
self.text.text = self.plistArray[randV];
[self.plistArray removeObjectAtIndex:randV];
}
}
-(IBAction)modal:(id)sender{
}
- (IBAction)container:(id)sender {
}
- (IBAction)shownext:(id)sender {
if ([plistArray count] == 0) {
self.text.text = #"Please Upgrade for more";
}
else {
////display random quote from array
int randV = arc4random() % self.plistArray.count;
self.text.text = self.plistArray[randV];
[self.plistArray removeObjectAtIndex:randV];
}
}
#end
And here is my plist structure there will be alot more data added here when finished tho
It's a little tough to understand the code, so I'll state this in general terms. If you have two arrays of strings (maybe your truth array and dare array), and you have a string that the user selected (this is the part that's unclear in your code -- is it self.text.text?) Let's just call it selectedString, then you can test:
if ([self.truthArray containsObject:selectedString]) {
// selectedString is from the truth array
} else if ([self.dareArray containsObject:selectedString]) {
// selectedString is from the dare array
} else {
// it's in neither array. maybe this is an error
}

Same object saved to NSUserDefaults over and over again when the NSMutableDictionary is different

It's driving me crazy, I did a log and I see the objects are different, but when I get then back from NSUserDefaults, all of the objects are the same.
My code:
- (void)breakTrapsToSave:(NSDictionary*)trapsDict firstTimeUpdate:(Boolean)firstTimeUpdate
{
// If traps already save
// we will get them from NSUserDefaults
// and then update them
if (!firstTimeUpdate)
{
allTraps = [self.sharedPrefs objectForKey:#"arrayOfAllTraps"];
}
// JSON Parsing
tempA = trapsDict[#"Envelope"];
tempB = tempA[#"Body"];
tempC = tempB[#"getTrapsResponse"];
tempD = tempC[#"getTrapsResult"];
tempE = tempD[#"TRAPS"];
self.lastUpdate = tempE[#"lastUpdate"];
[[NSUserDefaults standardUserDefaults] setObject:self.lastUpdate forKey:#"last_update"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"Traps latest updated at: %#", self.lastUpdate);
tempF = tempE[#"TRAP"];
if (tempF.count <= 0)
{
newTrapsUpdates = false;
NSLog(#"NO NEW TRAPS!");
}
else
{
newTrapsUpdates = true;
NSLog(#"NEW TRAPS FOUND");
[tempF enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
tempA = tempF[idx];
NSString *finalResult;
NSString *key;
NSMutableDictionary *singleTrap = [[NSMutableDictionary alloc] init];
for (int i=0; i < node.count; i++)
{
finalResult = tempA[node[i]];
key = node[i];
if ([finalResult length] <= 0)
{
finalResult = #"0";
}
singleTrap[key] = finalResult;
}
if (allTraps.count <= 0)
{
allTraps = [[NSMutableArray alloc] initWithObjects:singleTrap, nil];
}
else
{
[allTraps addObject:singleTrap];
}
counter = idx;
}];
allTraps = [[IDANNetroads sharedInstance] removeDuplicatedFromArray:allTraps];
// Save all traps
[[NSUserDefaults standardUserDefaults] setObject:allTraps forKey:#"arrayOfAllTraps"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"Total Traps: %d", allTraps.count);
NSLog(#"Total New Traps: %d", counter);
}
}
I did a log and I see allTraps[idx] = singleTrap; is different as it should be, but when I print the log for NSLog(#"allTraps: %#", allTraps); I see all of the objects are the last object.
EDIT:
Eventually, I replaced the singleTrap allocation and now it's inside the enumeration block:
NSMutableDictionary *singleTrap = [[NSMutableDictionary alloc] init];
And I added this code:
if (allTraps.count <= 0)
{
allTraps = [[NSMutableArray alloc] initWithObjects:singleTrap, nil];
}
else
{
[allTraps addObject:singleTrap];
}
So, the final code is edited.
Whatever singleTrap is, you're repeatedly mutating it and storing another reference to the same object in your allTraps array. You need to create (instantiate) a new item for each entry you want in your allTraps list.
It looks like singleTrap is an array of strings, so try:
allTraps[idx] = [singleTrap copy];

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