UIPickerView with two rows - ios

I am trying to make a simple converter for some unit stuff, and i can't seem to manage getting the data out of both columns and making them into a variable i can calculate with. I also get some errors, which i would really appreciate if anyone would look into. The errors are at the #pragma mark - PickerView Delegate, where i think about 90% of my code is wrong.
Here is the full .h file. (Hoping i did this the right way this time)
And here is the full project if anyone has got the time to look into it. http://www.mediafire.com/download.php?ss706o783ioa59u
#import "MainViewController.h"
#interface MainViewController ()
#end
#implementation MainViewController
#synthesize _convertFrom, _convertTo, _convertRates;
#synthesize dollarText, picker, resultLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_convertFrom = #[#"Australia (AUD)", #"China (CNY)",
#"France (EUR)", #"Great Britain (GBP)", #"Japan (JPY)"];
_convertRates = #[ #0.9922f, #6.5938f, #0.7270f,
#0.6206f, #81.57f];
_convertTo = #[#"Australia (AUD)", #"China (CNY)",
#"France (EUR)", #"Great Britain (GBP)", #"Japan (JPY)"];
_convertRates = #[ #0.9922f, #6.5938f, #0.7270f,
#0.6206f, #81.57f];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
//dont forget to put something in here later
}
- (IBAction)textFieldReturn:(id)sender {
[sender resignFirstResponder];
}
#pragma mark -
#pragma mark PickerView DataSource
- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component
{
if (component == 0) {
return [_convertFrom count];
}
return [_convertTo count];
}
- (NSString *) pickerView: (UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
if (component == 0) {
return [_convertFrom objectAtIndex:[pickerView selectedRowInComponent:0]];
}
return [_convertTo objectAtIndex:[pickerView selectedRowInComponent:1]];
}
#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
float from = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:0] floatValue]];
float to = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:1] floatValue]];
float input = [dollarText.text floatValue];
// This stuff is from some guide.
//float rate = [_convertRates[row] floatValue];
//float dollars = [dollarText.text floatValue];
//float result = dollars * rate;
NSString *resultString = [[NSString alloc] initWithFormat:
#"%.2f #% = %.2f %#", input, [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:0] floatValue]], result, [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:0] floatValue]]];
resultLabel.text = resultString;
}
#pragma mark - Flipside View
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showAlternate"]) {
[[segue destinationViewController] setDelegate:self];
}
}
#end
Thanks in advance :)

I just looked at your code, but still have some doubts about your calculation, but your braces was wrong and please implement it like this only:
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
float from = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:0]] floatValue];
float to = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:1]] floatValue];
float input = [dollarText.text floatValue];
// This stuff is from some guide.
float rate = from;
float dollars = input;
float result = dollars * rate;
NSString *resultString = [[NSString alloc] initWithFormat:
#"result = %f = %f * %f", result, dollars, rate];
resultLabel.text = resultString;
}
-(IBAction)clear
{
}

These two lines:
float from = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:0] floatValue]];
float to = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:1] floatValue]];
should be:
float from = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:0]] floatValue];
float to = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:1]] floatValue];
You have bracket in the wrong spot. And it looks like the 'resultString' line has the same problem, multiple times.

Related

How to set display time for each item using iCarousel when auto-scroll

As my title indicated, I want to know if there's a iCarousel delegate method as well as property that I can use to set display time for each item for my banner view when auto-scroll.
Previously, I used SDCycleScrollView for my banner view and I did it this way below:
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index {
BannerData *data = self.bannerDatas[index];
NSLog(#"***************cycleScrollView************************");
NSLog(#"index --> %ld", (long)index);
NSLog(#"banner data --> %#", data);
NSLog(#"banner data duration --> %d", data.duration);
cycleScrollView.autoScrollTimeInterval = data.duration;
}
data.duration is duration for each item to stay still.
How can I achieve this with iCarousel? Thanks in advance.
Here below are my iCarousel methods so far:
- (NSInteger)numberOfItemsInCarousel:(__unused iCarousel *)carousel
{
NSLog(#">>>>>>>>>number of items in Carousel --> %lu", (unsigned long)[self.bannerDatas count]);
return (NSInteger)[self.bannerDatas count];
}
- (UIView *)carousel:(__unused iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{
view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 520, 375)];
NSLog(#"url --> %#", [NSURL URLWithString:[self.netImages objectAtIndex:index]]);
[((UIImageView *)view)sd_setImageWithURL:[NSURL URLWithString:[self.netImages objectAtIndex:index]] placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
view.contentMode = UIViewContentModeCenter;
return view;
}
- (void)scrollToItemAtIndex:(NSInteger)index duration:(NSTimeInterval)duration
{
BannerData *data = self.bannerDatas[index];
NSLog(#"***************cycleScrollView************************");
NSLog(#"index --> %ld", (long)index);
NSLog(#"banner data --> %#", data);
NSLog(#"banner data duration --> %d", data.duration);
}
- (CGFloat)carousel:(__unused iCarousel *)carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value
{
//customize carousel display
switch (option)
{
case iCarouselOptionWrap:
{
//normally you would hard-code this to YES or NO
return YES;
}
case iCarouselOptionSpacing:
{
//add a bit of spacing between the item views
//return value * 1.05;
}
case iCarouselOptionFadeMax:
{
// if (self.carousel.type == iCarouselTypeCustom)
// {
// //set opacity based on distance from camera
// return 0.0;
// }
// return value;
}
case iCarouselOptionShowBackfaces:
case iCarouselOptionRadius:
case iCarouselOptionAngle:
case iCarouselOptionArc:
case iCarouselOptionTilt:
case iCarouselOptionCount:
case iCarouselOptionFadeMin:
case iCarouselOptionFadeMinAlpha:
case iCarouselOptionFadeRange:
case iCarouselOptionOffsetMultiplier:
case iCarouselOptionVisibleItems:
{
return value;
}
}
}
#pragma mark -
#pragma mark iCarousel taps
- (void)carousel:(__unused iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index
{
BannerData *data = self.bannerDatas[index];
if (![data.playlistId isEqualToString:#""]) { //Play Playlist
CategoryDetailData *detailData = [[CategoryDetailData alloc]init];
detailData.categoryId = data.playlistId;
RandomSecondVC *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"RandomSecondVC"];
vc.detailData = detailData;
NSLog(#"vc.detailData.categoryId --> %#", vc.detailData.categoryId );
vc.hidesBottomBarWhenPushed = YES; //????sanit
[self.navigationController pushViewController:vc animated:YES];
} else if (![data.url isEqualToString:#""]) { //Show webview
WebViewVC *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"WebViewVC"];
vc.hidesBottomBarWhenPushed = YES;
vc.navTitle = #"";
vc.urlString = data.url;
[self.navigationController pushViewController:vc animated:YES];
}else if (![data.videoId isEqualToString:#""]) { //Play video
VideoDetailVC *detailView = [self.storyboard instantiateViewControllerWithIdentifier:#"VideoDetailVC"];
detailView.videoId = data.videoId;
detailView.hidesBottomBarWhenPushed = YES; //????sanit
[self.navigationController pushViewController:detailView animated:YES];
}
}
Here below is how I place my Carousel view:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *tableCell = nil;
if (indexPath.section == 0) { //for banner
//++++++++++++++++++++??sanit iCarousel ver.1++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
NSLog(#"first section!!!!!!!!");
static NSString *BannerCellIdentifier = #"BannerTableViewCell"; //original
BannerTableViewCell *bannerCell = [tableView dequeueReusableCellWithIdentifier:BannerCellIdentifier]; //original
//BannerTableViewCell *bannerCell = [[BannerTableViewCell alloc]init];
[self setUpNetImages];
bannerCell.carouselView.type = iCarouselTypeCoverFlow2;
//bannerCell.carouselView.type = iCarouselTypeLinear;
//bannerCell.carouselView.autoscroll = 1; //?????sanit set autoscroll
bannerCell.carouselView.delegate = self;
bannerCell.carouselView.dataSource =self;
//??????sanit to fix banner timing issue first banner
//BannerData *data0 = self.bannerDatas[1]; //???santi
//self.cycleScrollView.autoScrollTimeInterval = data0.duration; // use this to fix timing issue of first slide
//[bannerCell.carouselView scrollToItemAtIndex:0 duration:data0.duration];
//bannerCell.carouselView.autoscroll = 0.8;
//[bannerCell.carouselView scrollToItemAtIndex:0 duration:5];
//[bannerCell.carouselView scrollToItemAtIndex:1 animated:YES];
[bannerCell.carouselView reloadData];
tableCell = bannerCell;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=//
} else { //for collection cell below
NSLog(#"not first section!!!!!!!! %d",(int)indexPath.section);
static NSString *MainHeaderCellIdentifier = #"MainHeaderTableViewCell";
MainHeaderTableViewCell *mainHeaderCell = (MainHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:MainHeaderCellIdentifier]; //original
mainHeaderCell.collectionView = (UICollectionView *)[mainHeaderCell viewWithTag:100];
mainHeaderCell.collectionView.delegate = self;
mainHeaderCell.collectionView.dataSource = self;
//NSLog(#"mainHeaderCell.index = %d",(int)mainHeaderCell.index);
//original
if (mainHeaderCell.collectionView == nil) {
NSLog(#"CollectionView Nil!!!!!!!");
}
tableCell = mainHeaderCell;
}
return tableCell;
}
Seems that iCarousel does not have that option, but, luckily, you can implement such functionality by yourself:
#property (nonatomic, strong) NSMutableDictionary *operations;
#property (nonatomic) BOOL isDragging;
- (void) carouselDidEndScrollingAnimation:(iCarousel *)carousel
{
if (!self.isDragging){
NSNumber *tag = #(carousel.tag);
[self.operations[tag] cancel];
self.operations[tag] = [NSBlockOperation blockOperationWithBlock:^{
double duration = [self durationForItemAtIndex:carousel.currentItemIndex inCarousel:carousel];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSInteger i = carousel.currentItemIndex + 1;
NSInteger next = i < carousel.numberOfItems ? i : 0;
[carousel scrollToItemAtIndex:next animated:YES];
});
}];
[(NSOperation*)(self.operations[tag]) start];
}
}
- (void) carouselWillBeginDragging:(iCarousel *)carousel
{
[self.operations[#(carousel.tag)] cancel];
self.isDragging = YES;
}
- (void) carouselDidEndDragging:(iCarousel *)carousel willDecelerate: (BOOL)decelerate
{
self.isDragging = NO;
}
- (double) durationForItemAtIndex:(NSInteger)index inCarousel:(iCarousel*)carousel
{
return <appropriate_duration_for_particular_carousel_and_item_index_in_it>;
}
- (void) startCarousel:(iCarousel*)carousel
{
[self carouselDidEndScrollingAnimation:carousel];
}
Update -[tableView:cellForRowAtIndexPath:] method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
<...>
if (indexPath.section == 0) {
<...>
bannerCell.carouselView.tag = indexPath.row;
[self startCarousel:bannerCell.carouselView];
} else {
<...>
}
return tableCell;
}
And don't forget to initialize the operations dictionary somewhere before usage:
self.operations = [NSMutableDictionary new];
However, all this is kind of draft - you may want to tune and upgrade these snippets according to your needs.

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];
}

Incorrect scrolling UITextView with NSAttributedString

I want to make a synchronized show lyric app and all lyric shown on a UITextView. In order to highlight current lyric I add background color to NSAttributedString of UITextView. All NSRange of lines stored in a NSArray.
My code is pretty simple, when button tapped move the highlight line down (via set contentOffset of UITextView). But here a strange problem occurred. In the beginning, the UITextView scroll properly but when contentOffset of UITextView greater then its frame.size.height it was fixed.
Here is my code:
//View controller
#import "ViewController.h"
#interface ViewController () {
NSUInteger globelIndex;
NSArray *textRanges;
NSMutableAttributedString *attributedText;
}
#property (weak, nonatomic) IBOutlet UITextView *lyricView;
#property (strong, nonatomic) NSTimer *mainTimer;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *rawText = [self readFile];
globelIndex = 0;
[self initTextLines:rawText];
attributedText = [[NSMutableAttributedString alloc] initWithString:rawText
attributes:#{NSBackgroundColorAttributeName: [UIColor orangeColor]}];
self.lyricView.attributedText = [attributedText copy];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)manualNextLine:(UIButton *)sender {
[self updateTextView];
}
- (IBAction)autoNextLineUsingNSTimer:(UIButton *)sender {
self.mainTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateTextView) userInfo:nil repeats:YES];
}
- (void)updateTextView {
if (self.lyricView.contentOffset.y >= self.lyricView.contentSize.height &&
self.mainTimer)
{
self.mainTimer = nil;
return;
}
NSMutableAttributedString *mat = [attributedText mutableCopy];
NSValue *value = [textRanges objectAtIndex:globelIndex];
[mat addAttribute:NSBackgroundColorAttributeName value:[UIColor whiteColor] range:[value rangeValue]];
self.lyricView.attributedText = [mat copy];
globelIndex += 1;
// self.textView.contentOffset = CGPointMake(self.textView.contentOffset.x, self.textView.contentOffset.y + 24);
// [self.textView scrollRangeToVisible:[value rangeValue]];
CGPoint newOffset = CGPointMake(self.lyricView.contentOffset.x, self.lyricView.contentOffset.y + 20);
[self.lyricView setContentOffset:newOffset animated:NO];
NSLog(#"[%# %#] h: %f b: %f a: %f", NSStringFromClass([self class]), NSStringFromSelector(_cmd), self.lyricView.contentSize.height, newOffset.y, self.lyricView.contentOffset.y);
}
#pragma mark - helper
- (void)initTextLines:(NSString *)rawText {
NSMutableArray *result = [#[] mutableCopy];
NSArray *t = [rawText componentsSeparatedByString:#"\r\n"];
__block int index = 0;
[t enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *s = obj;
NSRange range = NSMakeRange(index, s.length + 2);
[result addObject:[NSValue valueWithRange:range]];
index += s.length + 2;
}];
textRanges = [result copy];
}
- (NSString *)readFile {
NSError *error = nil;
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:#"二人の季節が-ささきのぞみ-想い" withExtension:#"lrc"];
NSString *content = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:&error];
if (error) {
if (DEBUG) NSLog(#"[%# %#] Error: %#", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
abort();
}
return content;
}
#end
All my code was in ViewController and StoryBoard has two UIButton and a UITextView.
What I wonder is "Why the UITextView.contentOffset cannot change when it greater than some size".
Maybe rewrite setContentOffset:animated is helpful for you!
Here is some sample code which you can borrow:
https://github.com/360/Three20/blob/master/src/Three20UI/Sources/TTTextView.m
#import "Three20UI/TTTextView.h"
// UI
#import "Three20UI/UIViewAdditions.h"
#implementation TTTextView
#synthesize autoresizesToText = _autoresizesToText;
#synthesize overflowed = _overflowed;
- (void)setContentOffset:(CGPoint)offset animated:(BOOL)animated {
if (_autoresizesToText) {
if (!_overflowed) {
// In autosizing mode, we don't ever allow the text view to scroll past zero
// unless it has past its maximum number of lines
[super setContentOffset:CGPointZero animated:animated];
} else {
// If there is an overflow, we force the text view to keep the cursor at the bottom of the
// view.
[super setContentOffset: CGPointMake(offset.x, self.contentSize.height - self.height)
animated: animated];
}
} else {
[super setContentOffset:offset animated:animated];
}
}
#end

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));
}
})}

how to change elements on UIpickerView pushing a button or pushing another button

I have an application, that in the main view, have 3 buttons, and the 2 firts buttons have to show an UIPickerView for a selection of event (one of them) and a selection of time (the second).
UIPickerViewDelegate only let me to implement the methods one time, so, how can I do for change the content of the UIPickerView.
Here is mi .m code:
#import "Home_ViewController.h"
#interface Home_ViewController ()
#end
#implementation Home_ViewController
#synthesize index,arrayHoras,arrayRutas,pickerView, rutaId, horas, botonHoras, botonRuta, hora;
- (IBAction)selectRuta:(id)sender {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[self.view addSubview:pickerView];
[UIView commitAnimations];
[pickerView setHidden:NO];
}
- (IBAction)horasBoton:(id)sender {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[self.view addSubview:pickerView];
[UIView commitAnimations];
[pickerView setHidden:NO];
}
- (void)viewDidLoad
{
[super viewDidLoad];
hora = 1;
arrayRutas = [[NSMutableArray alloc] init];
arrayHoras = [[NSMutableArray alloc] initWithObjects: #"1", #"2", #"3", #"4", #"5", #"6", #"7", #"8", #"9", #"10", #"11", #"12", nil];
sqlite3 *turutaDB;
NSArray *dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *databasePath = [[dirPath objectAtIndex:0] stringByAppendingPathComponent:#"turuta.db"];
NSLog(#"path de la bbdd: %#", databasePath);
if(sqlite3_open([databasePath UTF8String], &turutaDB)==SQLITE_OK) {
NSLog(#"2 Base de datos creada y abierta con exito");
} else {
NSLog(#"Ha fallado la apertura de la bbdd");
}
sqlite3_stmt *sentenciaRutas;
NSString *querySQLrutas = #"SELECT id,nombre FROM rutas";
if(sqlite3_prepare_v2(turutaDB, [querySQLrutas UTF8String], -1, &sentenciaRutas, NULL)==SQLITE_OK){
NSLog(#"Consulta preparada ok");
} else {
NSLog(#"Consulta ha fallado al preparar: %s", sqlite3_errmsg(turutaDB));
}
while (sqlite3_step(sentenciaRutas) == SQLITE_ROW) {
NSString *selectRutas = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(sentenciaRutas, 1)];
[arrayRutas addObject:selectRutas];
}
sqlite3_finalize(sentenciaRutas);
// [self.tabBarController.tabBar setHidden:YES];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if(!botonHoras.isTouchInside) {
return [arrayHoras count];
} else {
return [arrayRutas count];
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
if(!botonHoras.isTouchInside) {
return [arrayHoras objectAtIndex:row];
} else {
return [arrayRutas objectAtIndex:row];
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if (!botonHoras.isTouchInside) {
horas= [[arrayHoras objectAtIndex:row] intValue];
botonHoras.titleLabel.text = [NSString stringWithFormat:#"%d Horas", horas];
[self.pickerView removeFromSuperview];
} else {
//GMSPolylineOptions *optionsLine = [GMSPolylineOptions options];
GMSMutablePath *ruta = [GMSMutablePath path];
sqlite3 *turutaDB;
NSArray *dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *databasePath = [[dirPath objectAtIndex:0] stringByAppendingPathComponent:#"turuta.db"];
NSLog(#"path de la bbdd: %#", databasePath);
if(sqlite3_open([databasePath UTF8String], &turutaDB)==SQLITE_OK) {
NSLog(#"2 Base de datos creada y abierta con exito");
} else {
NSLog(#"Ha fallado la apertura de la bbdd");
}
sqlite3_stmt *sentenciaId;
NSString *querySQLid = [NSString stringWithFormat: #"SELECT id FROM rutas WHERE nombre = '%#'", [arrayRutas objectAtIndex:row]];
if(sqlite3_prepare_v2(turutaDB, [querySQLid UTF8String], -1, &sentenciaId, NULL)==SQLITE_OK){
NSLog(#"Consulta preparada ok");
} else {
NSLog(#"Consulta ha fallado al preparar: %s", sqlite3_errmsg(turutaDB));
}
while (sqlite3_step(sentenciaId) == SQLITE_ROW) {
NSString *id = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(sentenciaId, 0)];
rutaId = [id intValue];
NSLog(#"%d",rutaId);
}
sqlite3_finalize(sentenciaId);
sqlite3_stmt *sentenciaPolyLine;
NSString *querySQLpoliline =[NSString stringWithFormat: #"SELECT coordx,coordy FROM config_ruta WHERE id_ruta = %d", rutaId];
if(sqlite3_prepare_v2(turutaDB, [querySQLpoliline UTF8String], -1, &sentenciaPolyLine, NULL)==SQLITE_OK){
NSLog(#"Consulta preparada ok");
} else {
NSLog(#"Consulta ha fallado al preparar: %s", sqlite3_errmsg(turutaDB));
}
while (sqlite3_step(sentenciaPolyLine) == SQLITE_ROW) {
NSString *x = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(sentenciaPolyLine, 1)];
NSString *y = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(sentenciaPolyLine, 0)];
double coordx = [x doubleValue];
double coordy = [y doubleValue];
NSLog(#"%f | %f",coordy,coordx);
[ruta addCoordinate:CLLocationCoordinate2DMake(coordy, coordx)];
}
sqlite3_finalize(sentenciaPolyLine);
botonRuta.titleLabel.text = [arrayRutas objectAtIndex:row];
[self.pickerView removeFromSuperview];
[pickerView selectRow:0 inComponent:0 animated:YES];
}
}
- (IBAction)rutaboton:(id)sender {
}
Some help please...
You need to set a flag indicating which button was pressed. Then you check that flag in each of the picker view data source and delegate methods.
Add an int property to your class. In the selectRuta: method set the property to 1. In the horasBoton: method, set the property to 2.
Then you picker view method look something like this (this assumes your property was named buttonType):
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if(self.buttonType == 1) {
return [arrayRutas count];
} else {
return [arrayHoras count];
}
}

Resources