Button is on some devices visible and on some devices not visible - ios

A button in a tablecell is visible, when a check is true and not visible, when the check is false.
Here are the part of the function:
BOOL checked = [self checkObjekt:object];
if (checked == YES ) {
[cell.buttonUpload setHidden:NO];
[cell.buttonUpload setTitle:#"Geprüft, Upload!" forState:UIControlStateNormal];
[cell.buttonUpload setEnabled:YES];
} else {
[cell.buttonUpload setHidden:YES];
[cell.buttonUpload setTitle:#"Ungeprüft" forState:UIControlStateNormal];
[cell.buttonUpload setEnabled:NO];
}
I have proofed if the data from the object are correct. And in all databases are the value are true or yes, so the button should be visible. With the same database-file are only on some devices are the button not visible.
All Devices are on iOS 8.1.3 and they are iPad mini Retina.
Here is the full function:
- (void)configureCell:(MbsStartCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
Objekt *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSDate *rawDate = [object valueForKey:#"termin"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd.MM.yyyy"];
NSString *strLabelUhrzeitbis;
if (nil != object.uhrzeitbis && ![object.uhrzeitbis isEqualToString:#""])
{
strLabelUhrzeitbis = object.uhrzeitbis;
cell.labelDatum.text = [NSString stringWithFormat:#"%# zwischen %# und %#", [dateFormatter stringFromDate:rawDate], object.uhrzeit, strLabelUhrzeitbis];
}
else
{
cell.labelDatum.text = [NSString stringWithFormat:#"%# um %#", [dateFormatter stringFromDate:rawDate], object.uhrzeit];
}
NSSet *adressen = object.adressen;
NSArray *adressenArray = [adressen allObjects];
for (Adresse *adresse in adressenArray)
{
if ([adresse.typ isEqualToString:#"Baustelle"])
{
if (adresse.anschrift1 && ![adresse.anschrift1 isEqualToString:#""])
{
cell.labelAnschrift.text = [NSString stringWithFormat:#"%#", adresse.anschrift2];
} else {
cell.labelAnschrift.text = adresse.anschrift2;
}
cell.labelStrassePlzOrt.text = [NSString stringWithFormat:#"%#, %# %#", adresse.strasse, adresse.plz, adresse.ort];
}
}
cell.labelObjektnummer.text = [[object valueForKey:#"objektnr"] description];
cell.labelFilale.text = [NSString stringWithFormat:#"Filiale: %#, %#", object.filialname, object.objektanleger];
cell.labelAnrufer.text = [NSString stringWithFormat:#"Anrufer: %#", object.anrufer];
NSDate *rawSchadenstag = [object valueForKey:#"schadentag"];
NSDateFormatter *dateFormatterSchadenstag = [[NSDateFormatter alloc] init];
[dateFormatterSchadenstag setDateFormat:#"dd.MM.yyyy"];
cell.labelSchadentag.text = [NSString stringWithFormat:#"Schadenstag: %#", [dateFormatterSchadenstag stringFromDate:rawSchadenstag]];
cell.labelSchadensursache.text = [NSString stringWithFormat:#"Schadensursache: %#", object.schadensursache];
cell.labelSchadensursache.lineBreakMode = NSLineBreakByWordWrapping;
cell.labelSchadensursache.numberOfLines = 2;
NSString *strWeitererHinweis;
if (nil != object.weitererhinweis)
{
strWeitererHinweis = object.weitererhinweis;
}
else
{
strWeitererHinweis = #"Es sind keine weiteren Hinweise vorhanden";
}
cell.labelWeitererHinweis.text = [NSString stringWithFormat:#"Weiterer Hinweis: %#", strWeitererHinweis];
cell.labelWeitererHinweis.numberOfLines = 3;
cell.labelWeitererHinweis.lineBreakMode = NSLineBreakByWordWrapping;
int intTerminart = [object.terminart intValue];
switch (intTerminart) {
case 1: {
cell.backgroundColor = [UIColor whiteColor];
[cell.buttonUpload setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
break;
}
case 2: {
cell.backgroundColor = [UIColor blueColor];
[cell.buttonUpload setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
break;
}
case 4: {
cell.backgroundColor = [UIColor redColor];
[cell.buttonUpload setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
break;
}
case 5: {
cell.backgroundColor = [UIColor yellowColor];
[cell.buttonUpload setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
break;
}
case 6: {
cell.backgroundColor = [UIColor greenColor];
[cell.buttonUpload setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
break;
}
default:
break;
}
cell.selectionStyle = UITableViewCellSelectionStyleGray;
BOOL checked = [self checkObjekt:object];
if (checked == YES ) {
[cell.buttonUpload setHidden:NO];
[cell.buttonUpload setTitle:#"Geprüft, Upload!" forState:UIControlStateNormal];
[cell.buttonUpload setEnabled:YES];
} else {
[cell.buttonUpload setHidden:NO];
[cell.buttonUpload setTitle:#"Ungeprüft" forState:UIControlStateNormal];
[cell.buttonUpload setEnabled:YES];
}
}
Here is the checkObjekt Function:
- (BOOL)checkObjekt:(Objekt *)objekt {
if ([[objekt.wohneinheiten allObjects] count] == 0) {
return NO;
}
//Das Schadensformular für jede Wohneinheit wird in einer Schleife durchgearbeitet
for (Wohneinheit *wohneinheit in [objekt.wohneinheiten allObjects])
{
MbsAppDelegate *delegate = (MbsAppDelegate *)[[UIApplication sharedApplication] delegate];
NSEntityDescription *entityDescription = nil;
//Auswahl der richtigen Tabelle anhand der Terminart
if ([objekt.terminart integerValue] == 1)
{
entityDescription = [NSEntityDescription entityForName:#"Schaden" inManagedObjectContext:delegate.managedObjectContext];
}
else if ([objekt.terminart integerValue] == 2)
{
entityDescription = [NSEntityDescription entityForName:#"Leckortung" inManagedObjectContext:delegate.managedObjectContext];
}
else if ([objekt.terminart integerValue] == 4)
{
entityDescription = [NSEntityDescription entityForName:#"Aufbau" inManagedObjectContext:delegate.managedObjectContext];
}
else if ([objekt.terminart integerValue] == 5)
{
entityDescription = [NSEntityDescription entityForName:#"Zwischenmessung" inManagedObjectContext:delegate.managedObjectContext];
}
else if ([objekt.terminart integerValue] == 6)
{
entityDescription = [NSEntityDescription entityForName:#"Abbau" inManagedObjectContext:delegate.managedObjectContext];
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"wohneinheit == %#", wohneinheit];
[request setPredicate:predicate];
NSError *error;
NSArray *items = [delegate.managedObjectContext executeFetchRequest:request error:&error];
if (items == nil || [items count] != 1)
{
//Wenn kein Schadens- oder Leckortungsformular vorhanden ist, dann wird NO zurückgegeben
return NO;
}
else
{
//Durchlaufen der einzelnen Checked Spalten.
for (id item in items) {
int tempChecked = 0;
NSArray *checkedColumns = nil;
if ([objekt.terminart integerValue] == 1)
{
checkedColumns = self.checkedColumnsTerminart1;
}
else if ([objekt.terminart integerValue] == 2)
{
checkedColumns = self.checkedColumnsTerminart2;
}
else if ([objekt.terminart integerValue] == 4)
{
checkedColumns = self.checkedColumnsTerminart4;
}
else if ([objekt.terminart integerValue] == 5)
{
checkedColumns = self.checkedColumnsTerminart5;
}
else if ([objekt.terminart integerValue] == 6)
{
checkedColumns = self.checkedColumnsTerminart6;
}
for (NSString *checkedColumn in checkedColumns)
{
NSManagedObject *managedObject = (NSManagedObject *)item;
NSDictionary * attributes = [[managedObject entity] attributesByName];
NSArray *allKeys = [attributes allKeys];
if ([allKeys containsObject:checkedColumn]) {
NSNumber *checkedColumnValue = (NSNumber *)[item valueForKey:checkedColumn];
if (checkedColumnValue != [NSNumber numberWithInt:1]) {
tempChecked = 0;
}
else
{
tempChecked = 1;
}
} else {
tempChecked = 1;
}
}
if(tempChecked == 0)
{
return NO;
}
else
{
return YES;
}
}
}
}
return YES;
}

Related

UISwitch behavior changed in IOS 14 XCode Beta 4

Has anyone noticed with the changes added to UISwitch in Beta 4, that if you set a switches tag, for some reason it doesn't respect it? I add a switch programmatically to the accessory view of a TableView cell and once the cell is selected I access the switch to get it's tag to know which switch it was and the state that was changed.
Here are the code examples:
if (_showSwitch) {
if (cell.accessoryView == nil) {
cell.selectionStyle = UITableViewCellSelectionStyleNone;
switchview = [[UISwitch alloc]initWithFrame:CGRectZero];
switchview.tag = indexPath.row;
cell.accessoryView = switchview;
[switchview addTarget:self action:#selector(switchChanged:)
forControlEvents:UIControlEventValueChanged];
cell.backgroundColor = UIColor.systemGray2Color;
}
NSArray *strArray = [_tableDataSource[indexPath.row] componentsSeparatedByString:#"/"];
_row = indexPath.row;
_cellLabel = strArray[0];
cell.textLabel.text = _cellLabel;
_cellArray = [_cellArray arrayByAddingObject:(NSString *)_cellLabel];
if (_level >= 1) {
_deviceID = strArray[1];
_deviceArray = [_deviceArray arrayByAddingObject:_deviceID];
_lowcaseDeviceID = _deviceID = _deviceID.lowercaseString;
dictLookup = _statusDict[_lowcaseDeviceID];
if (_row >= 1) {
mycmdString = [mycmdString stringByAppendingString:#","];
}
mycmdString = [mycmdString stringByAppendingString:_deviceID];
UISwitch *switchView = (UISwitch *)cell.accessoryView;
[switchView setOn:NO animated:NO];
if ([dictLookup isEqualToString:#"ON"]) {
cell.textLabel.textColor = UIColor.systemGreenColor;
[switchView setOn:YES animated:YES];
}
_callForStatus = TRUE;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
- (IBAction)ControlView:(UISwitch *)sender {
ControlViewController *flController = [[ControlViewController alloc]
initWithNibName:#"ControlViewController" bundle:nil];
(flController.navigationItem).title = [NSString stringWithFormat:#"%# - %#", _deviceName, _device];
_level = _level += 1;
flController.deviceID = _device;
flController.deviceName = _deviceName;
flController.deviceState = #"OFF";
if ((sender.isOn) == YES) {
flController.deviceState = #"ON";
}
double delayInSeconds = 0.1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
[self presentViewController:flController animated:YES completion:nil];
});
}
- (void)switchChanged:(UISwitch *)sender {
bool mode;
UISwitch *switchControl = sender;
if (switchControl.isOn == YES) {
[switchControl setOn:YES animated:YES];
mode = TRUE;
[General playSound:#"Button Up.mp3"];
} else {
[switchControl setOn:NO animated:NO];
mode = FALSE;
[General playSound:#"Button Down.mp3"];
}
sender.highlighted = YES;
_callForStatus = TRUE;
[self executeSwitchAtRow:switchControl.tag forMode:mode];
// if (_level >= 1) [self startStepperTimer];
}
- (void)executeSwitchAtRow:(NSInteger)row forMode:(BOOL)onoff {
NSString *mode = #"OFF";
if (onoff) {
mode = #"ON";
}
NSString *device = _deviceArray[row];
Debug_1(#"Send Switch Change for device %# %#",device,mode);
NSString *execCommand = [NSString stringWithFormat:#"device %# %#", mode, device];
[[NSNotificationCenter defaultCenter] postNotificationName:#"sendMessageFromExternal" object:self
userInfo:#{ #"cmd": execCommand }];
if (_level >= 1) [self startStepperTimer];
}
...

Messages deleted in chat room re-appear after re-enter the chat room

This below code is fired when I press delete button after selecting messages I want to delete in chat room.
- (void)deleteButtonPressed:(id)sender {
if (arrayToDelete.count) {
for (NSString *str in arrayToDelete) {
NSLog(#"msgID --> %#",str);
[self.chatModel.dataSource removeObject:str]; //??? Remove data from the screen
[[FMDBManager sharedInstance] deleteMessageByMessageId:str]; //??? Delete data from database
}
[arrayToDelete removeAllObjects];
[self.chatTableView reloadData];
}
}
This line successfully removes selected messages from the chat room.
[self.chatModel.dataSource removeObject:str]; //??? Remove data from the screen
When I go out the chat room and re-enter, those messages still exist, so I have this line below.
[[FMDBManager sharedInstance] deleteMessageByMessageId:str]; //??? Delete data from database
I think the above line should delete those selected messages from the database but when I re-enter the chat room I still see those messages. Here below are related code to that.
- (void)deleteMessageByMessageId:(NSString *)messageId {
FMDatabase *db = [self getterDataBase];
[db open];
NSString *sqlString = [NSString stringWithFormat:#"DELETE FROM message WHERE messageId = '%#'",messageId];
BOOL status = [db executeUpdate:sqlString];
NSLog(#"Delete MessageById:%# Status:%d",messageId,status);
[db close];
}
I've found that when chat room calls viewDidLoad it will eventually call the method callBackGetChannelLogNew where server will sync-up data with chat room tableview and local database.
- (void)callBackGetChannelLogNew:(NSDictionary *)resultDataDic status:(enumAPI_STATUS)eAPI_STATUS {
if (isFirstTimeUpdate) {
}
if (eAPI_STATUS == API_STATUS_SUCCEE) {
NSString *readString=[NSString stringWithFormat:#"%#",resultDataDic[#"read_arr"]];
if ([readString isEqualToString:#""]) {
// NSLog(#"read_arr is empty");
}
else {
NSArray *read_arr=resultDataDic[#"read_arr"];
// Copy read_arr
self.readArray=[read_arr mutableCopy];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
[self dealWithReadArray:read_arr];
});
}
NSArray *data = [resultDataDic objectForKey:#"msg"];
if (data.count > 0) {
apiHaveData = YES;
} else {
apiHaveData = NO;
self.loadIngView.hidden = YES;
isLoadingData = NO;
return;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
// Reverse order of data
NSArray* reversedArray = [[data reverseObjectEnumerator] allObjects];
NSMutableArray *messageFromOtherArray = [NSMutableArray new];
NSMutableArray *messageAllArray = [NSMutableArray new];
for (int i = 0; i < reversedArray.count; i++) {
NSDictionary *_dic = reversedArray[i];
NSString *fromId = [_dic objectForKey:#"fid"];
NSString *message = [NSString stringWithFormat:#"%#",[_dic objectForKey:#"say"]];
if ([ObjectManager getChatMessageKindWithString:message] == MessageTypeText) {
message = [ObjectManager decryptWithString:message];
}
NSString *messageId = [_dic objectForKey:#"mid"];
NSString *toId = [_dic objectForKey:#"tid"];
NSDateFormatter *_formatter = [[NSDateFormatter alloc] init];
_formatter.dateFormat = #"yyyy-MM-dd HH:mm:ss.SSS";
NSDate *date_t = [NSDate dateWithTimeIntervalSince1970:[[_dic objectForKey:#"t"] doubleValue]/1000.0]; //換算成日期
NSString *stringDate = [_formatter stringFromDate:date_t];
NSString *sendDate = stringDate;
NSString *lid = _dic[#"lid"];
NSMutableDictionary *myDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:
fromId,#"fromId",
message,#"message",
messageId,#"messageId",
sendDate,#"sendDate",
toId,#"toId",
lid,#"lid",
nil];
NSString *isRead;
if (_chatRoomType == ChatRoomTypePrivate) {
if ([_dic[#"r"] intValue]) {
isRead = #"1";
myDic[#"isRead"] = isRead;
lastReadMessageId = [NSString stringWithFormat:#"%#",messageId];
}
}
if (i == 0) {
if (lidForAPI != [_dic[#"lid"] intValue]) {
lidForAPI = [_dic[#"lid"] intValue];
} else {
dispatch_async(dispatch_get_main_queue(), ^{
apiHaveData = NO;
self.loadIngView.hidden = YES;
isLoadingData = NO;
});
return ;
}
}
if (![myDic[#"fromId"] isEqualToString:[User sharedUser].account]) {
[messageFromOtherArray addObject:myDic];
}
if (_chatRoomType == ChatRoomTypeGroup) {
[myDic setObject:#"1" forKey:#"isGroupMessage"];
}
[myDic setObject:#"1" forKey:#"did_I_Read"];
[messageAllArray addObject:myDic];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self setupViewWithMessageArray:messageAllArray]; //???? Here server sync-up data with tableview
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
if (_chatRoomType == ChatRoomTypePrivate) {
if (messageFromOtherArray.count > 0 && isUplaodLastRead == NO) {
isUplaodLastRead = YES;
NSDictionary *lastReadMsgDic = messageFromOtherArray.lastObject;
[self callMsgReadAPI:lastReadMsgDic];
}
} else {
if (messageAllArray.count > 0 && isUplaodLastRead == NO) {
isUplaodLastRead = YES;
NSDictionary *lastReadMsgDic = messageAllArray.lastObject;
[self callMsgReadAPI:lastReadMsgDic];
}
}
self.chatModel.channelTopic = _topic;
NSArray *read_arr=resultDataDic[#"read_arr"];
[self dealMySendMessageReadedWithReadArray:read_arr AndMessageArray:messageAllArray];
[self saveMessageWithArray:messageAllArray]; //???? Here server sync-up data with local db
});
});
}
}
This lines will sync-up data from server to tableview
dispatch_async(dispatch_get_main_queue(), ^{
[self setupViewWithMessageArray:messageAllArray]; //???? Here server sync-up data with tableview
});
Here below is the method setupViewWithMessageArray
- (void)setupViewWithMessageArray:(NSArray *)messageAllArray {
if (!isFirstTimeUpdate) {
isFirstTimeUpdate = YES;
self.chatModel.dataSource = nil;
[self.chatTableView reloadData];
self.chatModel.dataSource = [[NSMutableArray alloc] init];
[self addMessageWithArray:messageAllArray];
[self.chatTableView reloadData];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.chatModel.dataSource.count-1 inSection:0];
[self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
} else {
[self addMessageWithArray:messageAllArray];
[self reloadTableViewWithoutMove];
}
self.loadIngView.hidden = YES;
isLoadingData = NO;
if (_chatRoomType == ChatRoomTypePrivate) {
if (lastReadMessageId) {
[self.chatModel setPrivateChatListAllReadFormMessageId:lastReadMessageId];
}
}
}
This line will sync-up data from server to local db
[self saveMessageWithArray:messageAllArray]; //???? Here server sync-up data with local db
Here below is the method saveMessageWithArray
- (void)saveMessageWithArray:(NSArray *)messageArray {
for (NSDictionary *myDic in messageArray) {
if (![[FMDBManager sharedInstance] didMessageExistWithMessageID:[myDic objectForKey:#"messageId"]]) {
[[FMDBManager sharedInstance] SaveMessage:myDic];
}
else {
NSString *mid=[NSString stringWithFormat:#"%#",myDic[#"messageId"]];
NSString *isRead = myDic[#"isReaed"];
if (isRead) {
[[FMDBManager sharedInstance] UpdateisReadWithMessageID:mid];
}
}
}
}
So I think now my question is how I can update messageAllArray with arrayToDelete before server sync-up?

Xcode 8 iOS 10 UITableView issue : UIImageView added from storyboard is rendering until table is scrolled

I have tableviews in my storyboard and it is working till Xcode 7.3, After Updating Xcode to 8, imageviews that are added in tableviewcell are not render first time until you scroll OR explicitly call reloadData. Imageviews are added from storyboard.
After scrolling
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ALContactCell *contactCell;
switch (indexPath.section)
{
case 0:
{
//Cell for group button....
contactCell = (ALContactCell *)[tableView dequeueReusableCellWithIdentifier:#"groupCell"];
//Add group button.....
UIButton *newBtn = (UIButton*)[contactCell viewWithTag:101];
[newBtn addTarget:self action:#selector(createGroup:) forControlEvents:UIControlEventTouchUpInside];
newBtn.userInteractionEnabled = YES;
}break;
case 1:
{
//Add rest of messageList
contactCell = (ALContactCell *)[tableView dequeueReusableCellWithIdentifier:#"ContactCell"];
[contactCell.mUserNameLabel setFont:[UIFont fontWithName:[ALApplozicSettings getFontFace] size:USER_NAME_LABEL_SIZE]];
[contactCell.mMessageLabel setFont:[UIFont fontWithName:[ALApplozicSettings getFontFace] size:MESSAGE_LABEL_SIZE]];
[contactCell.mTimeLabel setFont:[UIFont fontWithName:[ALApplozicSettings getFontFace] size:TIME_LABEL_SIZE]];
[contactCell.imageNameLabel setFont:[UIFont fontWithName:[ALApplozicSettings getFontFace] size:IMAGE_NAME_LABEL_SIZE]];
contactCell.unreadCountLabel.backgroundColor = [ALApplozicSettings getUnreadCountLabelBGColor];
contactCell.unreadCountLabel.layer.cornerRadius = contactCell.unreadCountLabel.frame.size.width/2;
contactCell.unreadCountLabel.layer.masksToBounds = YES;
//contactCell.mUserImageView.hidden = NO;
contactCell.mUserImageView.layer.cornerRadius = contactCell.mUserImageView.frame.size.width/2;
contactCell.mUserImageView.layer.masksToBounds = YES;
[contactCell.onlineImageMarker setBackgroundColor:[UIColor clearColor]];
UILabel* nameIcon = (UILabel*)[contactCell viewWithTag:102];
nameIcon.textColor = [UIColor whiteColor];
ALMessage *message = (ALMessage *)self.mContactsMessageListArray[indexPath.row];
ALContactDBService *contactDBService = [[ALContactDBService alloc] init];
ALContact *alContact = [contactDBService loadContactByKey:#"userId" value: message.to];
ALChannelDBService * channelDBService =[[ALChannelDBService alloc] init];
ALChannel * alChannel = [channelDBService loadChannelByKey:message.groupId];
if([message.groupId intValue])
{
ALChannelService *channelService = [[ALChannelService alloc] init];
[channelService getChannelInformation:message.groupId orClientChannelKey:nil withCompletion:^(ALChannel *alChannel)
{
contactCell.mUserNameLabel.text = [alChannel name];
contactCell.onlineImageMarker.hidden=YES;
}];
}
else
{
contactCell.mUserNameLabel.text = [alContact getDisplayName];
}
contactCell.mMessageLabel.text = message.message;
contactCell.mMessageLabel.hidden = NO;
if ([message.type integerValue] == [FORWARD_STATUS integerValue])
contactCell.mLastMessageStatusImageView.image = [ALUtilityClass getImageFromFramworkBundle:#"mobicom_social_forward.png"];
else if ([message.type integerValue] == [REPLIED_STATUS integerValue])
contactCell.mLastMessageStatusImageView.image = [ALUtilityClass getImageFromFramworkBundle:#"mobicom_social_reply.png"];
BOOL isToday = [ALUtilityClass isToday:[NSDate dateWithTimeIntervalSince1970:[message.createdAtTime doubleValue]/1000]];
contactCell.mTimeLabel.text = [message getCreatedAtTime:isToday];
[self displayAttachmentMediaType:message andContactCell:contactCell];
// here for msg dashboard profile pic
[nameIcon setText:[ALColorUtility getAlphabetForProfileImage:[alContact getDisplayName]]];
if([message getGroupId])
{
[contactCell.onlineImageMarker setHidden:YES];
}
else if(alContact.connected && [ALApplozicSettings getVisibilityForOnlineIndicator])
{
[contactCell.onlineImageMarker setHidden:NO];
}
else
{
[contactCell.onlineImageMarker setHidden:YES];
}
if(alContact.block || alContact.blockBy)
{
[contactCell.onlineImageMarker setHidden:YES];
}
BOOL zeroContactCount = (alContact.unreadCount.intValue == 0 ? true:false);
BOOL zeroChannelCount = (alChannel.unreadCount.intValue == 0 ? true:false);
if(zeroChannelCount || zeroContactCount)
{
contactCell.unreadCountLabel.text = #"";
[contactCell.unreadCountLabel setHidden:YES];
}
if(!zeroContactCount && [alContact userId] && (message.groupId.intValue == 0 || message.groupId == NULL)){
[contactCell.unreadCountLabel setHidden:NO];
contactCell.unreadCountLabel.text=[NSString stringWithFormat:#"%i",alContact.unreadCount.intValue];
}
else if(!zeroChannelCount && [message.groupId intValue]){
[contactCell.unreadCountLabel setHidden:NO];
contactCell.unreadCountLabel.text = [NSString stringWithFormat:#"%i",alChannel.unreadCount.intValue];
}
contactCell.mUserImageView.backgroundColor = [UIColor whiteColor];
if([message.groupId intValue])
{
[contactCell.mUserImageView setImage:[ALUtilityClass getImageFromFramworkBundle:#"applozic_group_icon.png"]];
NSURL * imageUrl = [NSURL URLWithString:alChannel.channelImageURL];
if(imageUrl)
{
[contactCell.mUserImageView sd_setImageWithURL:imageUrl];
}
nameIcon.hidden = YES;
}
else if(alContact.contactImageUrl)
{
NSURL * theUrl1 = [NSURL URLWithString:alContact.contactImageUrl];
[contactCell.mUserImageView sd_setImageWithURL:theUrl1];
nameIcon.hidden = YES;
}
else
{
nameIcon.hidden = NO;
[contactCell.mUserImageView sd_setImageWithURL:[NSURL URLWithString:#""]];
contactCell.mUserImageView.backgroundColor = [ALColorUtility getColorForAlphabet:[alContact getDisplayName]];
}
}break;
default:
break;
}
return contactCell;
}
After long hit and trials it worked after updating
dispatch_async(dispatch_get_main_queue(), ^{
contactCell.mUserImageView.layer.cornerRadius = contactCell.mUserImageView.frame.size.width/2;
contactCell.mUserImageView.layer.masksToBounds = YES;
});
OR
you can use context graphics to get circular image
But still need a prior solution

iOS "Control may reach end of non-void function"

Any idea why I am getting 2 errors of the below code of "Control may reach end of non-void function"? I had it working in a separate app but for some reason coming up with this error now.
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
switch (pickerView.tag) {
case kCATEGORYTYPEPICKERTAG:
return [categoryTypes count];;
break;
case kLOCATIONTYPEPICKERTAG:
return [locationTypes count];
break;
case kORIGINATORTYPEPICKERTAG:
return [originatorTypes count];
break;
case kDESTINATIONTYPEPICKERTAG:
return [destinationTypes count];
break;
case kSTATUSTYPEPICKERTAG:
return [statusTypes count];
break;
default:
break;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
switch (pickerView.tag) {
case kCATEGORYTYPEPICKERTAG:
return [categoryTypes objectAtIndex:row];
break;
case kLOCATIONTYPEPICKERTAG:
return [locationTypes objectAtIndex:row];
break;
case kORIGINATORTYPEPICKERTAG:
return [originatorTypes objectAtIndex:row];
break;
case kDESTINATIONTYPEPICKERTAG:
return [destinationTypes objectAtIndex:row];
break;
case kSTATUSTYPEPICKERTAG:
return [statusTypes objectAtIndex:row];
break;
default:
break;
}
}
Many Thanks
UPDATE
Full code:
#synthesize nameTextField, emailTextField, dateTextField, timeTextField, blankTextField, blankbTextField, mlabelcategory, messageTextView;
#synthesize name, emailaddress, date, time, blank, blankb, category, message;
- (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",
#"Brazilian", #"British", #"Cajun", #"Central American", #"Chicken",
#"Chinese", #"Cuban",
#"Ethiopian", #"French", #"Greek", #"German", #"Hamburgers",
#"Homestyle Cooking", #"Indian", #"Irish", #"Italian", #"Jamaican",
#"Japanese", #"Korean", #"Mexican", #"Middle Eastern", #"Pakistani",
#"Pancakes /Waffles", #"Persian", #"Pizza", #"Polynesian", #"Russian",
#"Sandwiches", #"Seafood", #"Scandinavian", #"Spanish", #"Soul Food",
#"South American", #"Steak", #"Vegetarian", #"Tex-Mex", #"Thai",
#"Vietnamese",#"Wild Game",nil];
originatorTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
#"Brazilian", #"British", #"Cajun", #"Central American", #"Chicken",
#"Chinese", #"Cuban",
#"Ethiopian", #"French", #"Greek", #"German", #"Hamburgers",
#"Homestyle Cooking", #"Indian", #"Irish", #"Italian", #"Jamaican",
#"Japanese", #"Korean", #"Mexican", #"Middle Eastern", #"Pakistani",
#"Pancakes /Waffles", #"Persian", #"Pizza", #"Polynesian", #"Russian",
#"Sandwiches", #"Seafood", #"Scandinavian", #"Spanish", #"Soul Food",
#"South American", #"Steak", #"Vegetarian", #"Tex-Mex", #"Thai",
#"Vietnamese",#"Wild Game",nil];
destinationTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
#"Brazilian", #"British", #"Cajun", #"Central American", #"Chicken",
#"Chinese", #"Cuban",
#"Ethiopian", #"French", #"Greek", #"German", #"Hamburgers",
#"Homestyle Cooking", #"Indian", #"Irish", #"Italian", #"Jamaican",
#"Japanese", #"Korean", #"Mexican", #"Middle Eastern", #"Pakistani",
#"Pancakes /Waffles", #"Persian", #"Pizza", #"Polynesian", #"Russian",
#"Sandwiches", #"Seafood", #"Scandinavian", #"Spanish", #"Soul Food",
#"South American", #"Steak", #"Vegetarian", #"Tex-Mex", #"Thai",
#"Vietnamese",#"Wild Game",nil];
statusTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
#"Brazilian", #"British", #"Cajun", #"Central American", #"Chicken",
#"Chinese", #"Cuban",
#"Ethiopian", #"French", #"Greek", #"German", #"Hamburgers",
#"Homestyle Cooking", #"Indian", #"Irish", #"Italian", #"Jamaican",
#"Japanese", #"Korean", #"Mexican", #"Middle Eastern", #"Pakistani",
#"Pancakes /Waffles", #"Persian", #"Pizza", #"Polynesian", #"Russian",
#"Sandwiches", #"Seafood", #"Scandinavian", #"Spanish", #"Soul Food",
#"South American", #"Steak", #"Vegetarian", #"Tex-Mex", #"Thai",
#"Vietnamese",#"Wild Game",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;
categoryTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(300,400,400,160)];
categoryTypePicker.tag = kCATEGORYTYPEPICKERTAG;
categoryTypePicker.showsSelectionIndicator = TRUE;
categoryTypePicker.dataSource = self;
categoryTypePicker.delegate = self;
categoryTypePicker.hidden = YES;
locationTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,250,400,160)];
locationTypePicker.backgroundColor = [UIColor blueColor];
locationTypePicker.tag = kLOCATIONTYPEPICKERTAG;
locationTypePicker.showsSelectionIndicator = TRUE;
locationTypePicker.hidden = YES;
locationTypePicker.dataSource = self;
locationTypePicker.delegate = self;
originatorTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,250,400,160)];
originatorTypePicker.backgroundColor = [UIColor blueColor];
originatorTypePicker.tag = kORIGINATORTYPEPICKERTAG;
originatorTypePicker.showsSelectionIndicator = TRUE;
originatorTypePicker.hidden = YES;
originatorTypePicker.dataSource = self;
originatorTypePicker.delegate = self;
destinationTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,250,400,160)];
destinationTypePicker.backgroundColor = [UIColor blueColor];
destinationTypePicker.tag = kDESTINATIONTYPEPICKERTAG;
destinationTypePicker.showsSelectionIndicator = TRUE;
destinationTypePicker.hidden = YES;
destinationTypePicker.dataSource = self;
destinationTypePicker.delegate = self;
statusTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,250,400,160)];
statusTypePicker.backgroundColor = [UIColor blueColor];
statusTypePicker.tag = kSTATUSTYPEPICKERTAG;
statusTypePicker.showsSelectionIndicator = TRUE;
statusTypePicker.hidden = YES;
statusTypePicker.dataSource = self;
statusTypePicker.delegate = self;
}
/*
// 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
{
if ( !locationTypePicker.hidden) {
locationTypePicker.hidden = YES;
}
if ( !categoryTypePicker.hidden) {
categoryTypePicker.hidden = YES;
}
if ( !originatorTypePicker.hidden) {
originatorTypePicker.hidden = YES;
}
if ( !destinationTypePicker.hidden) {
destinationTypePicker.hidden = YES;
}
if ( !statusTypePicker.hidden) {
statusTypePicker.hidden = YES;
}
}
#pragma mark -
#pragma mark picker methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return kPICKERCOLUMN;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
switch (pickerView.tag) {
case kCATEGORYTYPEPICKERTAG:
return [categoryTypes count];;
break;
case kLOCATIONTYPEPICKERTAG:
return [locationTypes count];
break;
case kORIGINATORTYPEPICKERTAG:
return [originatorTypes count];
break;
case kDESTINATIONTYPEPICKERTAG:
return [destinationTypes count];
break;
case kSTATUSTYPEPICKERTAG:
return [statusTypes count];
break;
default: return nil; break;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
switch (pickerView.tag) {
case kCATEGORYTYPEPICKERTAG:
return [categoryTypes objectAtIndex:row];
break;
case kLOCATIONTYPEPICKERTAG:
return [locationTypes objectAtIndex:row];
break;
case kORIGINATORTYPEPICKERTAG:
return [originatorTypes objectAtIndex:row];
break;
case kDESTINATIONTYPEPICKERTAG:
return [destinationTypes objectAtIndex:row];
break;
case kSTATUSTYPEPICKERTAG:
return [statusTypes objectAtIndex:row];
break;
default: return nil; break;
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (pickerView.tag == kCATEGORYTYPEPICKERTAG) {
NSString *categoryType = [categoryTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[categoryTypeBtn setTitle:categoryType forState:UIControlStateNormal];
}else if (pickerView.tag == kLOCATIONTYPEPICKERTAG) {
NSString *locationType = [locationTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[locationTypeBtn setTitle:locationType forState:UIControlStateNormal];
}else if (pickerView.tag == kORIGINATORTYPEPICKERTAG) {
NSString *originatorType = [originatorTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[originatorTypeBtn setTitle:originatorType forState:UIControlStateNormal];
}else if (pickerView.tag == kDESTINATIONTYPEPICKERTAG) {
NSString *destinationType = [destinationTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[destinationTypeBtn setTitle:destinationType forState:UIControlStateNormal];
}else if (pickerView.tag == kSTATUSTYPEPICKERTAG) {
NSString *statusType = [statusTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[statusTypeBtn setTitle:statusType forState:UIControlStateNormal];
}
}
-(IBAction) showLocationTypePicker{
if ( locationTypePicker.hidden) {
locationTypePicker.hidden = NO;
[self.view addSubview:locationTypePicker];
}
else {
locationTypePicker.hidden = NO;
[locationTypePicker removeFromSuperview];
}
if ( categoryTypePicker.hidden) {
categoryTypePicker.hidden = YES;
[self.view addSubview:categoryTypePicker];
}
else {
categoryTypePicker.hidden = YES;
[categoryTypePicker removeFromSuperview];
}
if ( originatorTypePicker.hidden) {
originatorTypePicker.hidden = YES;
[self.view addSubview:originatorTypePicker];
}
else {
originatorTypePicker.hidden = YES;
[originatorTypePicker removeFromSuperview];
}
if ( destinationTypePicker.hidden) {
destinationTypePicker.hidden = YES;
[self.view addSubview:destinationTypePicker];
}
else {
destinationTypePicker.hidden = YES;
[destinationTypePicker removeFromSuperview];
}
if ( statusTypePicker.hidden) {
statusTypePicker.hidden = YES;
[self.view addSubview:statusTypePicker];
}
else {
statusTypePicker.hidden = YES;
[statusTypePicker removeFromSuperview];
}
}
-(IBAction) showCategoryTypePicker{
if ( categoryTypePicker.hidden) {
categoryTypePicker.hidden = NO;
[self.view addSubview:categoryTypePicker];
}
else {
categoryTypePicker.hidden = NO;
[categoryTypePicker removeFromSuperview];
}
if ( locationTypePicker.hidden) {
locationTypePicker.hidden = YES;
[self.view addSubview:locationTypePicker];
}
else {
locationTypePicker.hidden = YES;
[locationTypePicker removeFromSuperview];
}
if ( originatorTypePicker.hidden) {
originatorTypePicker.hidden = YES;
[self.view addSubview:originatorTypePicker];
}
else {
originatorTypePicker.hidden = YES;
[originatorTypePicker removeFromSuperview];
}
if ( destinationTypePicker.hidden) {
destinationTypePicker.hidden = YES;
[self.view addSubview:destinationTypePicker];
}
else {
destinationTypePicker.hidden = YES;
[destinationTypePicker removeFromSuperview];
}
if ( statusTypePicker.hidden) {
statusTypePicker.hidden = YES;
[self.view addSubview:statusTypePicker];
}
else {
statusTypePicker.hidden = YES;
[statusTypePicker removeFromSuperview];
}
}
-(IBAction) showOriginatorTypePicker{
if ( originatorTypePicker.hidden) {
originatorTypePicker.hidden = NO;
[self.view addSubview:originatorTypePicker];
}
else {
originatorTypePicker.hidden = NO;
[originatorTypePicker removeFromSuperview];
}
if ( locationTypePicker.hidden) {
locationTypePicker.hidden = YES;
[self.view addSubview:locationTypePicker];
}
else {
locationTypePicker.hidden = YES;
[locationTypePicker removeFromSuperview];
}
if ( categoryTypePicker.hidden) {
categoryTypePicker.hidden = YES;
[self.view addSubview:categoryTypePicker];
}
else {
categoryTypePicker.hidden = YES;
[categoryTypePicker removeFromSuperview];
}
if ( destinationTypePicker.hidden) {
destinationTypePicker.hidden = YES;
[self.view addSubview:destinationTypePicker];
}
else {
destinationTypePicker.hidden = YES;
[destinationTypePicker removeFromSuperview];
}
if ( statusTypePicker.hidden) {
statusTypePicker.hidden = YES;
[self.view addSubview:statusTypePicker];
}
else {
statusTypePicker.hidden = YES;
[statusTypePicker removeFromSuperview];
}
}
-(IBAction) showDestinationTypePicker{
if ( destinationTypePicker.hidden) {
destinationTypePicker.hidden = NO;
[self.view addSubview:destinationTypePicker];
}
else {
destinationTypePicker.hidden = NO;
[destinationTypePicker removeFromSuperview];
}
if ( locationTypePicker.hidden) {
locationTypePicker.hidden = YES;
[self.view addSubview:locationTypePicker];
}
else {
locationTypePicker.hidden = YES;
[locationTypePicker removeFromSuperview];
}
if ( originatorTypePicker.hidden) {
originatorTypePicker.hidden = YES;
[self.view addSubview:originatorTypePicker];
}
else {
originatorTypePicker.hidden = YES;
[originatorTypePicker removeFromSuperview];
}
if ( categoryTypePicker.hidden) {
categoryTypePicker.hidden = YES;
[self.view addSubview:categoryTypePicker];
}
else {
categoryTypePicker.hidden = YES;
[categoryTypePicker removeFromSuperview];
}
if ( statusTypePicker.hidden) {
statusTypePicker.hidden = YES;
[self.view addSubview:statusTypePicker];
}
else {
statusTypePicker.hidden = YES;
[statusTypePicker removeFromSuperview];
}
}
-(IBAction) showStatusTypePicker{
if ( statusTypePicker.hidden) {
statusTypePicker.hidden = NO;
[self.view addSubview:statusTypePicker];
}
else {
statusTypePicker.hidden = NO;
[statusTypePicker removeFromSuperview];
}
if ( locationTypePicker.hidden) {
locationTypePicker.hidden = YES;
[self.view addSubview:locationTypePicker];
}
else {
locationTypePicker.hidden = YES;
[locationTypePicker removeFromSuperview];
}
if ( originatorTypePicker.hidden) {
originatorTypePicker.hidden = YES;
[self.view addSubview:originatorTypePicker];
}
else {
originatorTypePicker.hidden = YES;
[originatorTypePicker removeFromSuperview];
}
if ( destinationTypePicker.hidden) {
destinationTypePicker.hidden = YES;
[self.view addSubview:destinationTypePicker];
}
else {
destinationTypePicker.hidden = YES;
[destinationTypePicker removeFromSuperview];
}
if ( categoryTypePicker.hidden) {
categoryTypePicker.hidden = YES;
[self.view addSubview:categoryTypePicker];
}
else {
categoryTypePicker.hidden = YES;
[categoryTypePicker removeFromSuperview];
}
}
- (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];
}
This happens because in case you tag property doesn't fall into any of the cases, it goes to the default block which in turn won't return anything.
You need to return a default value (nil,0) in the default block:
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
NSInteger numberOfRows = 0;
switch (pickerView.tag) {
case kCATEGORYTYPEPICKERTAG: {
numberOfRows = [categoryTypes count];
break;
}
case kLOCATIONTYPEPICKERTAG: {
numberOfRows = [locationTypes count];
break;
}
case kORIGINATORTYPEPICKERTAG: {
numberOfRows = [originatorTypes count];
break;
}
case kDESTINATIONTYPEPICKERTAG: {
numberOfRows = [destinationTypes count];
break;
}
case kSTATUSTYPEPICKERTAG: {
numberOfRows = [statusTypes count];
break;
}
default: {
break;
}
}
return numberOfRows;
}
You'll also have to do this in the titleForRow method.
Also:
I prefer having minimal amount of returns and modifying a value
instead which I will return at the end
Enclosing cases in {}.

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