textFieldDidBeginEditing not fired at first tap - ios

When i tap the textfield textFieldDidBeginEditing starts to be fired after second tap. When I remove below code and after inside the textFieldDidBeginEditing method. It is fired at first tap. How can I make it fired at first tap?
[numKeyboard.view setFrame:CGRectMake(0,
self.view.frame.size.height-numKeyboard.view.frame.size.height, 320,
320)];
.m file:
#import "MainViewController.h"
#import "HastaDAO.h"
#import "YatanHastaBilgileriDAO.h"
#import "SettingViewController.h"
#import "Global.h"
#import <AudioToolbox/AudioServices.h>
#import "AlerjiModel.h"
#import "AlerjiDAO.h"
#import "NumKeyboard.h"
#interface MainViewController ()
{
int whichbtn;
}
#end
#implementation MainViewController
#synthesize player=_player;
#synthesize resultText1, resultText2,result,closeResult;
NSMutableArray *favTani;
HastaModel *yatanHastaBilgisi;
NSString *currentKey,*sound;
NSString *currentStringValue;
HastaModel *hasta;
int compareResult;
NSString *string=#"";
NSInteger didCompare=1;
UIImage *img;
NSString *str1,*str2;
NSInteger fromHistory=0;
-(void)viewDidAppear:(BOOL)animated{
if(fromHistory){
self.resultText1.text=str1;
self.resultText2.text=str2;
}
}
+(void)set_from_view:(NSInteger)history scanner:(NSInteger)scanner{
fromHistory=history;
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
if (textField == self.resultText2 && (![self.resultText1.text isEqualToString:#""] && ![self.resultText2.text isEqualToString:#""])){
[self destroyNumKeyboard];
[self compareTwoBarcode];
}
}
+(void)setResultTexts:(NSString*)str img:(UIImage*)image{
string=str;
img=[[UIImage alloc]init];
img=image;
}
-(void)compareTwoBarcode{
[self.resultText1 resignFirstResponder];
[self.resultText2 resignFirstResponder];
if(![self.resultText1.text isEqualToString:#""] && ![self.resultText2.text isEqualToString:#""] )
{
didCompare=1;
if ([resultText1.text isEqualToString:resultText2.text]) {
sound=#"%#/accept.mp3";
result.text = #"EŞLEŞİYOR";
result.backgroundColor = [UIColor colorWithRed:153/255.0 green:255/255.0 blue:51/255.0 alpha:0.85];
compareResult=1;
}
else
{
sound=#"%#/reject.mp3";
result.text = #"EŞLEŞMİYOR";
result.backgroundColor = [UIColor colorWithRed:255/255.0 green:0/255.0 blue:0/255.0 alpha:0.85];
compareResult=0;
}
[closeResult setHidden:FALSE];
[result setHidden:FALSE];
NSString *soundFilePath = [NSString stringWithFormat:sound, [[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = 1; //Infinite
if([SettingViewController getVolume])
[player play];
if([SettingViewController getVibrate]){
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Uyarı"
message:#"Barkod alanları dolu olmalıdır!"
delegate:nil
cancelButtonTitle:#"Tamam"
otherButtonTitles:nil];
[alert show];
}
}
-(void)setHistorySource{
NSString *word= self.resultText1.text;
NSString *pathhistory = [[self documentsDirectory] stringByAppendingPathComponent:#"history.plist"];
NSMutableArray *histList = [[NSMutableArray alloc] initWithContentsOfFile:pathhistory];
NSInteger ishist=0;
for (NSInteger i=[histList count]-1; i>=0;i--) {
NSDictionary *d = [histList objectAtIndex:i];
//NSString *patientName=[d objectForKey:#"PATIENT"];
NSString *name1=[d objectForKey:#"WORD1"];
NSString *name2=[d objectForKey:#"WORD2"];
if([name1 isEqualToString:self.resultText1.text] &&
[name2 isEqualToString:self.resultText2.text])
ishist=1;
}
if(ishist==0){
HastaModel*hmodel=[[HastaModel alloc]init];
NSMutableArray *arr=[HastaDAO getHasta:[self.resultText1.text intValue] yatanAyaktan:1];
if([arr count]==0)
arr=[HastaDAO getHasta:[self.resultText1.text intValue] yatanAyaktan:0];
if([arr count]){
hmodel=[arr objectAtIndex:0];
NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:
hmodel.Ad, #"PATIENT",
self.resultText1.text, #"WORD1",
self.resultText2.text,#"WORD2",
[NSString stringWithFormat:#"%ld",(long)compareResult ],#"EQUAL",
nil];
[histList addObject:dic];
if(![word isEqual:#""])
[histList writeToFile:pathhistory atomically:TRUE];
}
}
}
- (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation{
return(YES);
}
+(void)setbarcode1:(NSString*)barcode1 barcode2:(NSString*)barcode2{
str1=barcode1;
str2=barcode2;
}
- (void)viewDidLoad{
[super viewDidLoad];
[self.resultText1 setDelegate:self];
[self.resultText2 setDelegate:self];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return true;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
//if(textField==self.resultText2 && !resultText2.isFirstResponder){
UIView *dummyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
textField.inputView = dummyView;
int i=0;
for(UIViewController *vc in self.childViewControllers)
if([vc isKindOfClass:[NumKeyboard class]])
{
i++;
break;
}
if(!i){
NumKeyboard* numKeyboard = [[NumKeyboard alloc] initWithNibName:#"NumKeyboard" bundle:nil];
[numKeyboard.view setFrame:CGRectMake(0, self.view.frame.size.height-numKeyboard.view.frame.size.height, 320, 320)];
[self.view addSubview:numKeyboard.view];
[self addChildViewController:numKeyboard];
}
[self.view reloadInputViews];
//}
}
-(void)destroyNumKeyboard {
for(UIViewController *vc in self.childViewControllers){
if([vc isKindOfClass:[NumKeyboard class]])
{
[vc willMoveToParentViewController:nil];
[vc.view removeFromSuperview];
[vc removeFromParentViewController];
[self.parentViewController reloadInputViews];
}
break;
}
/*for (NumKeyboard *numKeyboardView in self.childViewControllers) {
if(numKeyboardView){
//UIButton son obje olduğu için
//[self.view.subviews.lastObject removeFromSuperview];
for (UIButton * btn in self.view.subviews) {
if([btn isKindOfClass:[UIButton class]])
if([btn.titleLabel.text isEqualToString:#"X"]){
[btn removeFromSuperview];
break;
}
}
[numKeyboardView willMoveToParentViewController:nil];
[numKeyboardView.view removeFromSuperview];
[numKeyboardView removeFromParentViewController];
[self reloadInputViews];
break;
}
}*/
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
-(void) closeHastaDetail{
[self.hastadetailview setHidden:TRUE];
}
-(void) closeHastaDetailDetail{
[self.hastadetailindetailview setHidden:TRUE];
}
-(void) openHastaDetailDetail{
[self.hastadetailindetailview setHidden:FALSE];
}
/*
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField.tag==2){
NSCharacterSet* numberCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
for (int i = 0; i < [string length]; ++i)
{
unichar c = [string characterAtIndex:i];
if (![numberCharSet characterIsMember:c])
{
return NO;
}
}
}
return YES;
}*/
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
currentKey=elementName;
currentStringValue=nil;
}
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
if(tabBar.tag == 0)
{
[self closeHastaDetail];
[self closeHastaDetailDetail];
}
}
- (NSString *)documentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) lastObject];
}
+(void)setDidCompareZero{
didCompare=0;
}
- (IBAction)closehastadetail:(id)sender {
[self.hastadetailview setHidden:TRUE];
[self performSelector:#selector(setHistorySource) withObject:nil afterDelay:0.1f];
}
- (IBAction)push_CompareBtn:(id)sender {
[self compareTwoBarcode];
}
- (IBAction) closeResult:(id)sender{
[closeResult setHidden:TRUE];
[result setHidden:YES];
if([SettingViewController getTekliCokluArama]==1){
}
}
- (IBAction)del_txt1:(id)sender {
self.resultText1.text=#"";
}
- (IBAction)del_txt2:(id)sender {
self.resultText2.text=#"";
}
- (IBAction) deleteResult:(id)sender{
//[resultImage1 setImage: [UIImage imageNamed:#"img1.png"]];
resultText1.text = #"";
//[resultImage2 setImage:[UIImage imageNamed:#"img2.png"]];
resultText2.text = #"";
}
- (IBAction) okDetailBtn:(id)sender{
[self.hastadetailindetailview setHidden:TRUE];
}
- (IBAction) showDetail:(id)sender{
[MainViewController set_from_view:0 scanner:0];
[self openHastaDetailDetail];
}
- (IBAction)setHastaDetail:(id)sender {
[self closeHastaDetailDetail];
self.hastadetailview.contentSize =CGSizeMake(320, 600);
[self.hastadetailview setContentOffset:CGPointMake(self.hastadetailview.contentOffset.x, 0)
animated:YES];
if(hasta==nil)
hasta=[[HastaModel alloc]init];
if([self.resultText1.text length]>0){
NSMutableArray *arr=[HastaDAO getHasta:[self.resultText1.text intValue] yatanAyaktan:1];
if(![arr count] && ![self.resultText1.text isEqualToString:self.hastaProtokol.text])
arr=[HastaDAO getHasta:[self.resultText1.text intValue] yatanAyaktan:0];
if([arr count])
{
hasta =[arr objectAtIndex:0];
if(![self.resultText1.text isEqualToString:self.hastaProtokol.text])
yatanHastaBilgisi=[YatanHastaBilgileriDAO yatanHastaBilgileri:hasta.Id];
self.hastaAd.text=hasta.Ad;
self.hastaAd.textAlignment=NSTextAlignmentRight;
self.hastaAd.font=[UIFont systemFontOfSize:18];
self.hastaProtokol.text=[NSString stringWithFormat:#"%ld", (long)hasta.Id];
self.hastaBolum.text=hasta.Bolum;
self.hastaOda.text=hasta.Oda;
self.hastaCinsiyet.text=hasta.Cinsiyet;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *strDate = [dateFormatter stringFromDate:yatanHastaBilgisi.DogumTarihi];
self.hastaDogumTarihi.text=strDate;
self.hastaYatak.text=hasta.Yatak;
self.hastaDoktor.text=yatanHastaBilgisi.Doktor;
if(hasta.LastOrderId>0)
{
NSMutableArray *arr1= [AlerjiDAO alerji:0 orderId:hasta.LastOrderId];
NSString*hAlerji=#"";
for(AlerjiModel *item in arr1 )
{
if(![hAlerji isEqualToString:#""])
hAlerji=[NSString stringWithFormat:#"%#,%#",hAlerji,item.Ad];
else
hAlerji=item.Ad;
}
self.hastaAlerji.text = hAlerji;
}else
self.hastaAlerji.text =#"";
[self.hastadetailview setHidden:FALSE];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#""
message:#"Hasta bulunamadı."
delegate:nil
cancelButtonTitle:#"Tamam"
otherButtonTitles:nil];
[alert show];
}
}
}#end

Related

iOS Multiple UIpickerView not showing Arrays

I have a hidden UIpickerView that should display a different Array depending on what button is pushed. The picker view shows up when the button is pushed but for some reason it doesn't show the Arrays in the picker view. I would be extremely grateful of any help!!!!
Here is the .m file:
#import "ViewController.h"
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
#define GeoLocation TRUE // FALSE for no latitude/longitude information
#define kPICKERCOLUMN 1
typedef NS_ENUM(NSInteger, PickerType) {
CATEGORY_PICKER,
LOCATION_PICKER,
ORIGINATOR_PICKER,
DESTINATION_PICKER,
STATUS_PICKER
};
#define kPICKERCOLUMN 1
#define kPICKER_TAG 101
#interface ViewController ()
#end
#implementation ViewController
{
UIPickerView *picker;
PickerType pickerType;
}
#synthesize nameTextField, emailTextField, dateTextField, timeTextField, blankTextField, blankbTextField, mlabelcategory, messageTextView, categoryTypeBtn;
#synthesize name, emailaddress, date, time, blank, blankb, category, message, email, button;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
categoryTypes = [[NSArray alloc] initWithObjects:#"Appetizers",#"Breakfast",#"Dessert",#"Drinks",
#"Main Dish/Entree", #"Salad", #"Side Dish", #"Soup", #"Snack",
#"Baby Food", #"Pet Food",nil];
locationTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue"
,nil];
originatorTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
nil];
destinationTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
nil];
statusTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
nil];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
nameTextField.text = nil;
emailTextField.text = nil;
dateTextField.text = nil;
timeTextField.text = nil;
blankTextField.text = nil;
blankbTextField.text = nil;
mlabelcategory.text = nil;
messageTextView.text = nil;
picker = [[UIPickerView alloc] initWithFrame:CGRectMake(100,100,400,160)];
picker.showsSelectionIndicator = TRUE;
picker.dataSource = self;
picker.delegate = self;
picker.hidden = YES;
[self.view addSubview:picker];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)eve
{
picker.hidden = YES;
}
#pragma mark -
#pragma mark picker methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return kPICKERCOLUMN;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
switch (pickerType) {
case CATEGORY_PICKER:
return [categoryTypes count];;
break;
case LOCATION_PICKER:
return [locationTypes count];
break;
case ORIGINATOR_PICKER:
return [originatorTypes count];
break;
case DESTINATION_PICKER:
return [destinationTypes count];
break;
case STATUS_PICKER:
return [statusTypes count];
break;
default: return -1;
break;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
switch (pickerType) {
case CATEGORY_PICKER:
return [categoryTypes objectAtIndex:row];
break;
case LOCATION_PICKER:
return [locationTypes objectAtIndex:row];
break;
case ORIGINATOR_PICKER:
return [originatorTypes objectAtIndex:row];
break;
case DESTINATION_PICKER:
return [destinationTypes objectAtIndex:row];
break;
case STATUS_PICKER:
return [statusTypes objectAtIndex:row];
break;
default: return nil;
break;
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
switch (pickerType) {
case CATEGORY_PICKER: {
NSString *categoryType = [categoryTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[categoryTypeBtn setTitle:categoryType forState:UIControlStateNormal];
break;
}
case LOCATION_PICKER: {
NSString *locationType = [locationTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[locationTypeBtn setTitle:locationType forState:UIControlStateNormal];
break;
}
case ORIGINATOR_PICKER: {
NSString *originatorType = [originatorTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[originatorTypeBtn setTitle:originatorType forState:UIControlStateNormal];
break;
}
case DESTINATION_PICKER: {
NSString *destinationType = [destinationTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[destinationTypeBtn setTitle:destinationType forState:UIControlStateNormal];
break;
}
case STATUS_PICKER:{
NSString *statusType = [statusTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[statusTypeBtn setTitle:statusType forState:UIControlStateNormal];
break;
}
default:
break;
}
}
-(IBAction) showLocationTypePicker{
pickerType = LOCATION_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
-(IBAction) showCategoryTypePicker{
pickerType = CATEGORY_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
-(IBAction) showOriginatorTypePicker{
pickerType = ORIGINATOR_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
-(IBAction) showDestinationTypePicker{
pickerType = DESTINATION_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
-(IBAction) showStatusTypePicker{
pickerType = STATUS_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
#pragma - getting info from the UI
//NSString *test = nil;
- (IBAction)checkData:(id)sender
{
/*
name = nameTextField.text;
surname = surnameTextField.text;
bornDate = bornDateTextField.text;
address = addressTextField.text;
zipCode = zipTextField.text;
email = emailTextField.text;
*/
//NSLog(#" Name: %# \n Surname: %# \n Date of Birth: %# \n Address: %# \n Post Code: %# \n email: %# \n", name, surname, bornDate, address, zipCode, email);
unsigned int x,a = 0;
NSMutableString *emailmessage; //stringa variabile
emailmessage = [NSMutableString stringWithFormat: #""]; //le stringhe mutabili vanno inizializzate in questo modo!
for (x=0; x<7; x++)
{
switch (x) {
case 0:
if (nameTextField.text == nil) {
[emailmessage appendString:#"Name, "];
a=1;
}
break;
case 1:
if (emailTextField.text == nil)
{
[emailmessage appendString:#"Email Address, "];
a=1;
}
break;
case 2:
if (dateTextField.text == nil)
{
[emailmessage appendString:#"Date of Near Miss, "];
a=1;
}
break;
case 3:
if (timeTextField.text == nil)
{
[emailmessage appendString:#"Time of Near Miss, "];
a=1;
}
break;
case 4:
if (blankTextField.text == nil)
{
[emailmessage appendString:#"Post Code, "];
a=1;
}
break;
case 5:
if (blankbTextField.text == nil)
{
[emailmessage appendString:#"Email, "];
a=1;
}
break;
case 6:
if (mlabelcategory.text == nil)
{
[emailmessage appendString:#"Category, "];
a=1;
}
break;
case 7:
if (messageTextView.text == nil)
{
[emailmessage appendString:#"Observation Description, "];
a=1;
}
break;
default:
break;
}
}
NSLog (#"Email Message: %#", emailmessage);
if (a == 1) {
NSMutableString *popupError;
popupError = [NSMutableString stringWithFormat: #"Per inviare compilare i seguenti campi: "];
[popupError appendString:emailmessage]; //aggiungo i miei errori
[popupError appendString: #" grazie della comprensione."]; //
NSLog(#"%#", popupError);
UIAlertView *chiamataEffettuata = [[UIAlertView alloc]
initWithTitle:#"ATTENTION" //titolo del mio foglio
message:popupError
delegate:self
cancelButtonTitle:#"Ok, correggo" //bottone con cui si chiude il messaggio
otherButtonTitles:nil, nil];
[chiamataEffettuata show]; //istanza per mostrare effettivamente il messaggio
}
else
{
name = nameTextField.text;
emailaddress = emailTextField.text;
date = dateTextField.text;
time = timeTextField.text;
blank = blankTextField.text;
blankb = blankbTextField.text;
category = mlabelcategory.text;
message = messageTextView.text;
NSMutableString *nearmissreport;
nearmissreport = [NSMutableString stringWithFormat: #"<br><br> <b>Name:</b> %# <br> <b>Email Address:</b> %# <br> <b>Date of Near Miss:</b> %# <br> <b>Time of Near Miss:</b> %# <br> <b>Post Code:</b> %# <br> <b>Email Address:</b> %# <br> <b>Category:</b> %# <br><b>Observation Description:</b> %# <br>", name, emailaddress, date, time, blank, blankb, category, message];
NSLog(#"Near Miss Report: %#", nearmissreport);
NSMutableString *testoMail;
testoMail = [NSMutableString stringWithFormat: nearmissreport];
NSLog(#"%#", testoMail);
//MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject: name];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"paul.haddell#bbmmjv.com",nil];
//NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com",#"third#example.com", nil];
//NSArray *bccRecipients = [NSArray arrayWithObjects:#"four#example.com",nil];
[picker setToRecipients:toRecipients];
//[picker setCcRecipients:ccRecipients];
//[picker setBccRecipients:bccRecipients];
// Attach an image to the email.
//NSString *path = [[NSBundle mainBundle] pathForResource:#"ipodnano" ofType:#"png"];
//NSData *myData = [NSData dataWithContentsOfFile:path];
//[picker addAttachmentData:myData mimeType:#"image/png" fileName:#"ipodnano"];
// Fill out the email body text.
//NSMutableString *emailBody;
testoMail = [NSMutableString stringWithFormat: #"%#", testoMail];
[picker setMessageBody:testoMail isHTML:YES]; //HTML!!!!!!
// Present the mail composition interface.
[self presentViewController:picker animated:YES completion:nil];
}
}
// The mail compose view controller delegate method
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error
{
[self dismissModalViewControllerAnimated:YES];
}
#pragma mark - Mandare email
/*
- (void)sendMail:(NSMutableString*)testoMail{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Reclutamento pompieri"];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"reda.bousbah#gmail.com",nil];
//NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com",#"third#example.com", nil];
//NSArray *bccRecipients = [NSArray arrayWithObjects:#"four#example.com",nil];
[picker setToRecipients:toRecipients];
//[picker setCcRecipients:ccRecipients];
//[picker setBccRecipients:bccRecipients];
// Attach an image to the email.
//NSString *path = [[NSBundle mainBundle] pathForResource:#"ipodnano" ofType:#"png"];
//NSData *myData = [NSData dataWithContentsOfFile:path];
//[picker addAttachmentData:myData mimeType:#"image/png" fileName:#"ipodnano"];
// Fill out the email body text.
NSString *emailBody = #"It is raining in sunny California!";
[picker setMessageBody:emailBody isHTML:NO];
// Present the mail composition interface.
[self presentViewController:picker animated:YES completion:nil];
}
*/
#pragma mark - methods to control the keyboard
- (IBAction)backgroundTap:(id)sender //method for resign the keyboard when the background is tapped
{
[nameTextField resignFirstResponder];
[emailTextField resignFirstResponder];
[dateTextField resignFirstResponder];
[timeTextField resignFirstResponder];
[blankTextField resignFirstResponder];
[blankbTextField resignFirstResponder];
[mlabelcategory resignFirstResponder];
[messageTextView resignFirstResponder];
}
- (IBAction)doneButtonPressed:(id)sender
{
NSLog( #"done button pressed");
[sender resignFirstResponder];
}
#end
Many Thanks

Content not loading on horizontal scroll view

Hi I am building an app in which I want my contents to be displayed on a view which is horizontally scroll-able.
I have implemented the following code for it:
-(void)DownLoadData:(NSString *)indexSelect
{
self._parserForNewsDetail = [afaqsParser getInstance];
[[afaqsParser getInstance] setCacheNeed:TRUE];
[self._parserForNewsDetail parseWithUrl:[_arrUrlLinks objectAtIndex:[indexSelect integerValue]] UrlTypefor:nil];
NSDictionary *resultDic;
resultDic = [[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0];
NSLog(#"Detail Dic = %#",[resultDic description]);
if (resultDic== NULL || resultDic ==nil)
{
//Check internet here
[[SharedUtilities getInstance]RemoveActivityIndicatorView];
[SharedUtilities ShowAlert:#"No Data Found" title:nil withView:self.view];
return;
}
[self performSelectorOnMainThread:#selector(SetValuesInUserInterface:) withObject: resultDic waitUntilDone:NO];
[[SharedUtilities getInstance]RemoveActivityIndicatorView];
}
-(void)DownloadNext:(NSString *)indexSelect
{
resultDic = [[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0];
NSURL *imgurl =[NSURL URLWithString:[[Dic valueForKey:#"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSArray *subviewsArr = [self.view subviews];
for (int i=0; i<[subviewsArr count]; i++) {
if ([[subviewsArr objectAtIndex:i] isKindOfClass:[ImageDownLoader class]]) {
}
}
[self loadScrollView];
}
-(void)SetValuesInUserInterface:(NSDictionary *)Dic
{
self._imageView1.layer.cornerRadius = 4;
self._imageView1.clipsToBounds = YES;
self._imageView1.tag = 999;
NSURL *imgurl =[NSURL URLWithString:[[Dic valueForKey:#"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
self._imageView1.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:imgurl]];
NSArray *subviewsArr = [self.view subviews];
for (int i=0; i<[subviewsArr count]; i++) {
if ([[subviewsArr objectAtIndex:i] isKindOfClass:[ImageDownLoader class]]) {
[[subviewsArr objectAtIndex:i] removeFromSuperview];
}
}
if ([[Dic valueForKey:#"image"] isEqual:#""])
{
_imageView1.hidden=YES;
_txtView.frame=CGRectMake(4.0f,95.0f,_txtView.frame.size.width,_txtView.frame.size.height );
NSLog(#"NO IMAGE");
}
else{
_imageView1.hidden=NO;
_imageView1.frame=CGRectMake(4.0f,95.0f,310.0f,180.0f );
// _txtView.frame=CGRectMake(4.0f,316.0f,310.0f,159.0f );
_txtView.frame=CGRectMake(4.0f,316.0f,_txtView.frame.size.width,_txtView.frame.size.height );
NSLog(#"IMAGE VISIBLE");
}
self._scrollView.scrollEnabled = YES;
self._scrollView.showsVerticalScrollIndicator = YES;
self._scrollView.showsHorizontalScrollIndicator = YES;
self._header.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:18];
[self._header setText: [Dic valueForKey:#"header"]];
self._header.textColor=[UIColor blackColor];
[self._Writer setText:[Dic valueForKey:#"AUTHOR"]];
[self._kicker setText:[Dic valueForKey:#"kicker"]];
[self._txtView setText:[Dic valueForKey:#"ARTICLE_BODY"]];
NSString *writer;
if ([[Dic valueForKey:#"AUTHOR"] length]>2)
{
writer=[NSString stringWithFormat:#"%#, ",[Dic valueForKey:#"AUTHOR"]];
}
else
{
writer=#"";
}
[self._Writer setText:str];
[_txtView sizeToFit]; //added
[_txtView layoutIfNeeded]; //added
CGRect frame = self._txtView.frame;
self._txtView.frame = frame;
[_txtView setScrollEnabled:NO];
self._scrollView.contentSize = CGSizeMake(320,440+frame.size.height);
_titleLabel.frame= CGRectMake(0, self._scrollView.contentSize.height-119, [[UIScreen mainScreen] bounds].size.width, 40);
_titleLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:1];
_titleLabel.textColor = [UIColor whiteColor];
_titleLabel.textAlignment = NSTextAlignmentCenter;
_titleLabel.font = [UIFont fontWithName:#"Helvetica" size:13.5];
_titleLabel.numberOfLines=2;
[self._scrollView addSubview:_titleLabel];
[self loadScrollView];
}
-(void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidLoad
{
[self DownLoadData:resultDic];
UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(loadScrollView)];
rightRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[rightRecognizer setNumberOfTouchesRequired:1];
//add the your gestureRecognizer , where to detect the touch..
[_scrollView addGestureRecognizer:rightRecognizer];
UISwipeGestureRecognizer *leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(loadScrollView)];
leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[leftRecognizer setNumberOfTouchesRequired:1];
[_scrollView addGestureRecognizer:leftRecognizer];
}
- (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
[self btnPreviousClick];
[self loadScrollView];
}
- (void)leftSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
NSLog(#"leftSwipeHandle");
[self btnNextClick];
[self loadScrollView];
}
-(IBAction)btnNextClick
{
btnPreviousNews.userInteractionEnabled=TRUE;
if(count!=[_arrUrlLinks count] -1)
{
if(count==[_arrUrlLinks count]-2)
{
btnNextNews.userInteractionEnabled=FALSE;
[btnNextNews setImage:[UIImage imageNamed:#"arrow2_next.png"] forState:UIControlStateNormal];
}
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow1_prev.png"] forState:UIControlStateNormal];
count=count +1;
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",count+1,[_arrUrlLinks count]];
NSLog(#"next %d",count);
[self performSelectorInBackground:#selector(DownLoadData:) withObject:[NSString stringWithFormat:#"%d",count]];
}
else{
btnNextNews.userInteractionEnabled=FALSE;
}
}
-(void)btnPreviousClick
{
btnNextNews.userInteractionEnabled=TRUE;
if(count==0)
{
btnPreviousNews.userInteractionEnabled=FALSE;
}
else{
if(count==1)
{
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
btnPreviousNews.userInteractionEnabled=FALSE;
}
[btnNextNews setImage:[UIImage imageNamed:#"arrow1_next.png"] forState:UIControlStateNormal];
count=count-1;
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",count+1,[_arrUrlLinks count]];
NSLog(#"previous %d",count);
[self performSelectorInBackground:#selector(DownLoadData:) withObject:[NSString stringWithFormat:#"%d",count]];
}
}
-(void)loadScrollView
{
_scrollView.contentSize = CGSizeMake(0, _scrollView.frame.size.height);
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < [_arrUrlLinks count]; i++) {
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
count=1;
// a page is the width of the scroll view
_scrollView.pagingEnabled = YES;
_scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * [_arrUrlLinks count], _scrollView.frame.size.height);
_scrollView.showsHorizontalScrollIndicator =YES;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.scrollsToTop = NO;
_scrollView.delegate = self;
pageControl.numberOfPages = [_arrUrlLinks count];
pageControl.currentPage = 0;
[_scrollView addSubview:_txtView];
[_txtView setText:[Dic valueForKey:#"ARTICLE_BODY"]];
[controller.view addSubview:_txtView];
// pages are created on demand
// load the visible page
// load the page on either side to avoid flashes when the user starts scrolling
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}
- (void)loadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= [_arrUrlLinks count])
return;
// replace the placeholder if necessary
controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
NSString *deviceType = [UIDevice currentDevice].model;
if([deviceType isEqualToString:#"iPhone"])
{
controller = [[MyViewController alloc] initWithNibName:#"MyViewController" bundle:nil];
}
else{
controller = [[MyViewController alloc] initWithNibName:#"MyViewController_ipad" bundle:nil];
}
[controller initWithPageNumber:page];
// [controller.view addSubview:_txtView];
// [controller.view addSubview:_imageview];
NSLog(#"loadscrollviewwithpage");
[viewControllers replaceObjectAtIndex:page withObject:controller];
// [controller release];
}
// add the controller's view to the scroll view
if (nil == controller.view.superview) {
CGRect frame = _scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
// _txtView.frame=frame;
// _imageview.frame=frame;
// _txtView.frame=CGRectMake(4.0f,316.0f,310.0f,159.0f );
_txtView=#"hello";
// [controller.view addSubview:_txtView];
[_imageView1 addSubview:controller.view];
// [_txtView addSubview:controller.view];
// [scrollView addSubview:controller.view];
NSLog(#"loadscrollviewwithpage................>>>>>>>>>>>>");
// [self._header setText: [Dic valueForKey:#"header"]];
// [self DownLoadData:resultDic];
//[self SetValuesInUserInterface:Dic];
[self DownloadNext:resultDic];
}
}
- (void)unloadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= [_arrUrlLinks count]) return;
controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller != [NSNull null]) {
if (nil != controller.view.superview)
[controller.view removeFromSuperview];
[viewControllers replaceObjectAtIndex:page withObject:[NSNull null]];
// [controller.view addSubview:_txtView];
// [controller.view addSubview:_imageview];
NSLog(#"Unloadscrollviewwithpage");
// [[NSURLCache sharedURLCache] removeAllCachedResponses];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
if (pageControlUsed) {
// do nothing - the scroll was initiated from the page control, not the user dragging
return;
}
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = _scrollView.frame.size.width;
int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
// NSLog(#"current page %d",page);
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self unloadScrollViewWithPage:page - 2];
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
[self unloadScrollViewWithPage:page + 2];
count=page+1;
// [self newCountTitleSet];
// A possible optimization would be to unload the views+controllers which are no longer visible
}
// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollViewLoc
{
CGFloat pageWidth = scrollViewLoc.frame.size.width;
CGPoint translation = [scrollViewLoc.panGestureRecognizer translationInView:scrollViewLoc.superview];
int page = floor((scrollViewLoc.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
if(translation.x > 0)
{
if(_strCurrentNewsSelect!=0)
{
if(page==0)
{
NSLog(#"OK");
NSLog(#"scrollviewwillbegindragging=0");
[self DownLoadDataPrevious:[_strCurrentNewsSelect.integervalue]-1];
}
}
else{
if(page==1)
{
NSLog(#"previous button");
[self btnPreviousClick];
}
}
} else
{
// [_txtView setText:[Dic valueForKey:#"ARTICLE_BODY"]];
// [controller.view addSubview:_txtView];
// [controller.view addSubview:_txtView];
// [controller.view addSubview:_imageview];
NSLog(#"loadscrollviewwithpage else");
[self btnPreviousClick];
NSLog(#"previous news");
// if(galleryItemClick+1!=[arrGallaeryUrl count])
//
// {
//
if(page+1==[_arrUrlLinks count])
//
{
//
NSLog(#"====....>>>>>>>");
}
count=count+1;
}
}
By using this code I am able to create the view controllers according to my array count[_arrUrlLinks] but the contents are not loaded on these views. On my first view I can only see an image view in black color rest of the views are blank.
How can I get the contents loaded on these views?

IOS dev: Just need help in exc_bad_access error

Help, my app is showing thread 1 error exc_bad_access(code=1, address=0x2000001) on the last curly brace of my PlayViewController.
Note: this happen when I click the continue button on my GuessViewController. The continue button calls the the PlayViewController.
What i already did:
enabled ZOMBIE
close db
my GuessViewController:
#import "GuessViewController.h"
#import "PlayViewController.h"
#import "ViewController.h"
#interface GuessViewController ()
#end
#implementation GuessViewController
#synthesize userInput = _userInput;
#synthesize gword;
#synthesize gletter;
int score = 0;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_userInput.delegate = self;
self.scoreLabel.text = [NSString stringWithFormat:#"%d", score];
// Do any additional setup after loading the view.
}
-(void)touchesBegan:(NSSet*)touches withEvent: (UIEvent *) event{
[_userInput resignFirstResponder];
}
-(BOOL)textFieldShouldReturn: (UITextField*)textField {
if(textField){
[textField resignFirstResponder];
}
return NO;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)checkAnswer:(id)sender {
NSLog(#"%#", gword);
NSLog(#"%#", gletter);
NSString *temp = self.userInput.text;
unichar temp2 = [temp characterAtIndex: 0];
NSString *userletter= [NSString stringWithFormat:#"%C", temp2];
NSString *message1 = #"The word is ";
NSString *message2= [NSString stringWithFormat:#"%#", gword];
NSString *fm = [message1 stringByAppendingString:message2];
if([userletter isEqualToString:gletter]){
UIAlertView *checkAlert = [[UIAlertView alloc] initWithTitle:#"Got it Right" message:fm delegate:self cancelButtonTitle:#"Continue" otherButtonTitles:#"Back to Main Menu", nil];
score++;
self.scoreLabel.text = [NSString stringWithFormat:#"%d", score];
[checkAlert show];
}else{
UIAlertView *checkAlert = [[UIAlertView alloc] initWithTitle:#"Wrong" message:fm delegate:self cancelButtonTitle:#"Continue" otherButtonTitles:#"Back to Main Menu", nil];
[checkAlert show];
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex ==0){
PlayViewController *playViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"Play"];
[self presentViewController:playViewController animated:YES completion: Nil];
} else {
ViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:#"Main"];
[self presentViewController:viewController animated:YES completion: Nil];
}
}
#end
My PlayViewController:
#import "PlayViewController.h"
#import "GuessViewController.h"
#import <sqlite3.h>
#import "Word.h"
#interface PlayViewController ()
#end
#implementation PlayViewController
#synthesize thewords;
NSString *word;
NSTimer *myTimer;
int randomIndex;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[self wordList];
[super viewDidLoad];
// Do any additional setup after loading the view.
self.listChar.text = #" ";
int r = (arc4random()%[self.thewords count]);
word = [self.thewords objectAtIndex:r];
NSLog(#"%#", word);
randomIndex = (arc4random()%word.length);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)startGame:(id)sender {
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(listLetter:) userInfo:nil repeats:YES];
}
- (void)listLetter:(NSTimer *)timer
{
static int i = 0;
unichar letter;
if(randomIndex == i){
letter = ' ';
} else {
letter = [word characterAtIndex: i];
}
self.listChar.text = [NSString stringWithFormat:#"%C", letter];
if (++i == word.length) {
[timer invalidate];
i = 0;
GuessViewController *guessViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"Guess"];
//passing some data
guessViewController.word = word;
guessViewController.letter = [NSString stringWithFormat:#"%C", [word characterAtIndex: randomIndex]];
[self presentViewController:guessViewController animated:YES completion: Nil];
}
}
-(NSMutableArray *) wordList {
thewords = [[NSMutableArray alloc] initWithCapacity:26];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"LetterHunter.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success){
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)){
NSLog(#"An error has occured");
}
const char *sql = "SELECT * FROM WordList";
sqlite3_stmt*sqlStatement;
if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL)!=SQLITE_OK){
NSLog(#"Problem with prepare statement1");
} else {
while(sqlite3_step(sqlStatement) == SQLITE_ROW){
Word *word = [[Word alloc]init];
word.wordfromdb = [NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)];
[thewords addObject: word.wordfromdb];
}
}
sqlite3_finalize(sqlStatement);
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement2");
}
#finally {
sqlite3_close(db);
}
}
#end
As suggested below, I tried doing this instead but still there's the error
while(sqlite3_step(sqlStatement) == SQLITE_ROW){
NSString *temp = #"";
temp = [NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)];
[thewords addObject: temp;
}
From debug stack, it's a problem about autorelease. And I think the problem maybe in
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)){
I can't find db define. So I think it should be a instance property.
Try this:
DbClass *tempDb = nil;
if(!(sqlite3_open([dbPath UTF8String], &tempDb) == SQLITE_OK)){
self.db = tempDb;
What is wordfromdb? If it is string variable or any other datatype then add directly that into an array...
I think there is not need to create word object here as anyway your are not storing word object in array.
It looks to me an issue with word object. You are crating word object but adding its property only and not entire object.

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

Truncated tweets iOS

I am putting a twitter feed in my app and no matter what I have tried to do to get the tweets to display in their entirety, I have not been entirely successful. Most tweets show up fine but it's the really long ones that have given me a headache. I thought it was because I was somehow not getting enough lines in my textLabel, but I noticed that if a user has elongated their tweet by hitting enter multiple times the tweets would show up fine. Which leads me to believe somehow it is truncating after a certain amount of characters. I don't know if I'm doing something wrong or if this is just an issue with twitter. If anyone can see anything in my code that is wrong, or could be changed to fix this, please let me know. Thank you
#import "TwitterFeedTVC.h"
#import "TweetVC.h"
#import <QuartzCore/QuartzCore.h>
#import "GTMNSString+HTML.h"
#define REFRESH_HEADER_HEIGHT 52.0f
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 10.0f
#implementation TwitterFeedTVC
#synthesize textPull, textRelease, textLoading, refreshHeaderView, refreshLabel, refreshArrow, refreshSpinner, twitterFeedName, twitterFeedTitle;
- (id)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self != nil)
{
[self setupStrings];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self != nil)
{
[self setupStrings];
}
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self != nil)
{
[self setupStrings];
}
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.twitterFeedTitle.text = self.twitterFeedName;
self.navigationItem.title = self.twitterFeedName;
[self fetchTweets];
[self addPullToRefreshHeader];
}
- (void)fetchTweets
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://api.twitter.com/1/statuses/user_timeline.json?include_rts=true&screen_name=johnnelm9r&count=100"]];
if (data == nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning"
message:#"Twitter Is Not Responding. Please Try Again Later!"
delegate:self
cancelButtonTitle:#"Kali Baby"
otherButtonTitles: nil];
[alert show];
}
else
{
NSError *error;
tweets = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (void)viewDidUnload
{
[super viewDidUnload];
textPull = nil;
textRelease = nil;
textLoading = nil;
refreshHeaderView = nil;
refreshLabel = nil;
refreshArrow = nil;
refreshSpinner = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tweets.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSString *text = [tweet objectForKey:#"text"];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), CGFLOAT_MAX);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
CGFloat height = MAX(size.height, 44.0f);
return height + ((CELL_CONTENT_MARGIN * 2) + 9);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TweetCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[dateFormatter setDateFormat:#"EEE MMM dd HH:mm:ss +0000 yyyy"];
NSDate *currentDate = [dateFormatter dateFromString:[tweet objectForKey:#"created_at"]];
NSDate *todayDate = [NSDate date];
NSString *date = [dateFormatter stringFromDate:currentDate];
double timeInterval = [currentDate timeIntervalSinceDate:todayDate];
timeInterval = timeInterval * -1;
if (timeInterval < 1)
{
date = #"never";
}
else if (timeInterval <60)
{
date = #"less than a minute ago";
}
else if (timeInterval <3600)
{
int diff = round(timeInterval / 60);
date = [NSString stringWithFormat:#"%d minutes ago", diff];
}
else if (timeInterval < 86400)
{
int diff = round(timeInterval / 60 / 60);
date = [NSString stringWithFormat:#"%d hours ago", diff];
}
else if (timeInterval < 2629743)
{
int diff = round(timeInterval / 60 / 60 / 24);
date = [NSString stringWithFormat:#"%d days ago", diff];
}
else
{
date = #"never";
}
cell.textLabel.text = [[tweet objectForKey:#"text"] gtm_stringByUnescapingFromHTML];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", date];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *imageUrl = [[tweet objectForKey:#"user"] objectForKey:#"profile_image_url"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [UIImage imageWithData:data];
[cell addSubview:cell.imageView];
});
});
return cell;
}
- (void)setupStrings
{
textPull = #"Pull Down To Be Fresh...";
textRelease = #"Release To Be Fresh...";
textLoading = #"Getting Loaded...";
}
- (void)addPullToRefreshHeader
{
refreshHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0 - REFRESH_HEADER_HEIGHT, 320, REFRESH_HEADER_HEIGHT)];
refreshHeaderView.backgroundColor = [UIColor clearColor];
refreshLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, REFRESH_HEADER_HEIGHT)];
refreshLabel.backgroundColor = [UIColor clearColor];
refreshLabel.font = [UIFont boldSystemFontOfSize:12.0];
refreshLabel.textAlignment = UITextAlignmentCenter;
refreshArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"KrizzOpener.png"]];
refreshArrow.frame = CGRectMake(floorf((REFRESH_HEADER_HEIGHT - 27) / 2),
(floorf(REFRESH_HEADER_HEIGHT - 44) / 2),
27, 44);
refreshSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
refreshSpinner.frame = CGRectMake(floorf(floorf(REFRESH_HEADER_HEIGHT - 20) / 2), floorf((REFRESH_HEADER_HEIGHT - 20) / 2), 20, 20);
refreshSpinner.hidesWhenStopped = YES;
[refreshHeaderView addSubview:refreshLabel];
[refreshHeaderView addSubview:refreshArrow];
[refreshHeaderView addSubview:refreshSpinner];
[self.tableView addSubview:refreshHeaderView];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
if (isLoading) return;
isDragging = YES;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (isLoading) {
if (scrollView.contentOffset.y > 0)
self.tableView.contentInset = UIEdgeInsetsZero;
else if (scrollView.contentOffset.y >= -REFRESH_HEADER_HEIGHT)
self.tableView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (isDragging && scrollView.contentOffset.y < 0) {
[UIView beginAnimations:nil context:NULL];
if (scrollView.contentOffset.y < -REFRESH_HEADER_HEIGHT) {
refreshLabel.text = self.textRelease;
} else {
refreshLabel.text = self.textPull;
}
[UIView commitAnimations];
}
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (isLoading) return;
isDragging = NO;
if (scrollView.contentOffset.y <= -REFRESH_HEADER_HEIGHT)
{
[self startLoading];
}
}
- (void)startLoading {
isLoading = YES;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
self.tableView.contentInset = UIEdgeInsetsMake(REFRESH_HEADER_HEIGHT, 0, 0, 0);
refreshLabel.text = self.textLoading;
refreshArrow.hidden = YES;
[refreshSpinner startAnimating];
[UIView commitAnimations];
[self refresh];
}
- (void)stopLoading {
isLoading = NO;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.3];
[UIView setAnimationDidStopSelector:#selector(stopLoadingComplete:finished:context:)];
self.tableView.contentInset = UIEdgeInsetsZero;
UIEdgeInsets tableContentInset = self.tableView.contentInset;
tableContentInset.top = 0.0;
self.tableView.contentInset = tableContentInset;
[UIView commitAnimations];
}
- (void)stopLoadingComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
refreshLabel.text = self.textPull;
refreshArrow.hidden = NO;
[refreshSpinner stopAnimating];
}
- (void)refresh {
[self fetchTweets];
[self performSelector:#selector(stopLoading) withObject:nil afterDelay:2.7];
}
#pragma mark - Table view delegate
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"tweetVC"])
{
NSInteger row = [[self tableView].indexPathForSelectedRow row];
NSDictionary *tweet = [tweets objectAtIndex:row];
TweetVC *tweetVC = segue.destinationViewController;
tweetVC.detailItem = tweet;
}
}
After a lot of investigation I found an article somewhere that said there is a difference between the text key and the retweeted_status.text key. The tweets being truncated were, in fact, retweets from the user using the text key. However, the retweeted_status.text key is only the tweet that was retweeted, without the user who originally tweeted it. That sucks because the retweeted_status.text key is NOT truncated. Ahhh, the joys of programming. Hopefully the new twitter API will address this. I hope this answer helps somebody.
Here is the link to what I found in case anyone is interested: http://code.google.com/p/twitter-api/issues/detail?id=2261
I haven't gone through your code, but I thought of mentioning this point that Twitter only allows tweet 140 characters long! This is the basic rule of a tweet. So no matter what you do tweet with mode than 140 characters will be truncated.
I hope this is not the issue?

Resources