UISearch bar changes results after searching - iphone

i am implementing search bar in a tableview but after search my address is changed from actual address, what should i do now
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
filteredListResults = [[NSMutableArray alloc] init];
GWTG *gwtg ;
for (gwtg in listResults)
{
NSRange nameRange = [gwtg.celebrity_name rangeOfString:text options:NSCaseInsensitiveSearch];//NSCaseInsensitiveSearch
NSRange descriptionRange = [gwtg.location_name rangeOfString:text options:NSCaseInsensitiveSearch];
if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
{
[filteredListResults addObject:gwtg];
}
}
}
[tblSearch reloadData];
}

Related

How to retrieve 10-10 contacts from address book

I want to implement for getting or loading 10 contacts at a time from address book.Any possibility to retrieve all contacts from address book but display them 10-10 contacts at a time.I am retrieving image,first name,last name of all iphone contacts.I want to implement this to email retrive email contacts also like 10-10 email contacts.
Here is my sample code:
SData *imageData = (NSData *)CFBridgingRelease(ABPersonCopyImageDataWithFormat(ref, kABPersonImageFormatThumbnail)) ;
CFStringRef firstName1, lastName1;
firstName1 = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName1 = ABRecordCopyValue(ref, kABPersonLastNameProperty);
NSString *name=[[NSString alloc]init];
if ([[NSString stringWithFormat:#"%#",firstName1] isEqualToString:#"(null)"] && [[NSString stringWithFormat:#"%#",lastName1] isEqualToString:#"(null)"])
{
name = #"No Name";
}
else if([[NSString stringWithFormat:#"%#",firstName1] isEqualToString:#"(null)"] && ![[NSString stringWithFormat:#"%#",lastName1] isEqualToString:#"(null)"])
{
name = [NSString stringWithFormat:#"%#",lastName1];
}
else
{
name = [NSString stringWithFormat:#"%#",firstName1];
}
name= [ name capitalizedString];
EmailandCotactsModel *emailmodel=[[EmailandCotactsModel alloc]init];
emailmodel.emailemailstring=(__bridge NSString *)(contno);
emailmodel.emailusernamestring=name;
if(!imageData)
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"NoImage" ofType:#"png"];
NSData *photoData = [NSData dataWithContentsOfFile:path];
emailmodel.emailimagesData=photoData;
}
else
{
emailmodel.emailimagesData=imageData;
}
[emailarray addObject:emailmodel];
callsmsDataBool=NO;
NSLog(#"table email count %d and i %d",emailarray.count,tablecountint);
if(emailarray.count==tablecountint)
{
NSLog(#"table email reload");
tablecountint=tablecountint+10;
dispatch_async( dispatch_get_global_queue(0,0),^{
[self reloadtable];
});
NSLog(#"perform selection in bg");
}
}
}
[self.tableview reloadData];
if(!emailarray.count && [socialstring isEqualToString:#"Email"])
{
selectedlabel.text=#"Emails not found";
}
else if(emailarray.count && [socialstring isEqualToString:#"Email"])
{
// selectedlabel.text=#"Email";
selectedlabel.text=[NSString stringWithFormat:#"%ld",nPeople];
}
else if(!emailarray.count && [socialstring isEqualToString:#"SMS"])
{
selectedlabel.text=#"Phone no's not found";
}
else if(emailarray.count && [socialstring isEqualToString:#"SMS"])
{
selectedlabel.text=#"SMS";
}
else
{
selectedlabel.text=#"";
}
[tableview reloadData];
Any valuable suggestions will be appreciated....
Thanks in advance.
After getting all contacts in one array copy ten contacts to another array and cal table reload method with that new array by calling this method initially lowerlimit = 0 and upperlimit=10;
-(void)tabledataloadingmethod
{
for (lowerlimit=0+lowerlimit; lowerlimit<upperlimit; lowerlimit++)
{
if (lowerlimit<[self.array1 count])
{
OBJECT *obj=[self.array1 objectAtIndex:lowerlimit];
[self.array2 addObject:obj];
}
}
[self.tbleview reloadData];
}
in table delagete method cellforrowatindex use this
if ([self.array2 count]==indexPath.row)
{
UITableViewCell *cell1=[self.tbleview dequeueReusableCellWithIdentifier:#"cells"];
if(cell1==nil)
{
cell1=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"Cells"];
}
cell1.textLabel.textColor = [UIColor whiteColor];
cell1.textLabel.text=#"Loading more...";
[self performSelector:#selector(loadmorecells) withObject:nil afterDelay:0.2];
return cell1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self.array2 count]>0 && ([self.array2 count]<[self.array1 count]))
{
return [self.array2 count]+1;
}
else
{
return [self.array2 count];
}
}
here we increment lowerlimit and upperlimit in loadmorecells method
-(void)loadmorecells
{
lowerlimit = upperlimit;
upperlimit = upperlimit +10;
[self tabledataloadingmethod];
}

How do I get a list of the user's contacts in iOS 6?

I have been using the following code for a few years now and it has always worked, but it looks like with iOS 6 it doesn't anymore. How do I get a list of all contacts on an iOS 6 device?
ABAddressBookRef myAddressBook = ABAddressBookCreate();
NSMutableArray *people = (__bridge_transfer NSMutableArray *)ABAddressBookCopyArrayOfAllPeople(myAddressBook);
CFRelease(myAddressBook);
// repeat through all contacts in the inital array we loaded
for(int i=0; i<[people count]; i++)
{
NSString *aName;
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:i]), kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:i]), kABPersonLastNameProperty);
if (([firstName isEqualToString:#""] || [firstName isEqualToString:#"(null)"] || firstName == nil) &&
([lastName isEqualToString:#""] || [lastName isEqualToString:#"(null)"] || lastName == nil))
{
// do nothing
}
else
{
aName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
if ([firstName isEqualToString:#""] || [firstName isEqualToString:#"(null)"] || firstName == nil)
{
aName = [NSString stringWithFormat:#"%#", lastName];
}
if ([lastName isEqualToString:#""] || [lastName isEqualToString:#"(null)"] || lastName == nil)
{
aName = [NSString stringWithFormat:#"%#", firstName];
}
[self.tableItems addObject:aName];
}
}
[self.tableItems sortUsingSelector:#selector(compare:)];
In ios6 you need to ask for permission to read the AddressBook, otherwise you'll get nil. Use something like this:
- (BOOL)askContactsPermission {
__block BOOL ret = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS6
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRef addressBook = ABAddressBookCreate();
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
ret = granted;
dispatch_semaphore_signal(sema);
});
if (addressBook) {
CFRelease(addressBook);
}
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_release(sema);
}
else { // we're on iOS5 or older
ret = YES;
}
return ret;
}
If this method returns NO, bad luck, you won't be able to access the AB. I'm locking with a semaphore here because I don't want to continue with my app if the user does not allow the AB. There other methods, just check the API.
You do need to ask the user for permission which will trigger a prompt to the user when you do so. Here's another way to do this using execution blocks to handle the result, also makes the usage of it version agnostic if you need to query your current access status from common code.
I implement an access manager like so
AppContactsAccessManager.h
#import <AddressBook/AddressBook.h>
typedef enum
{
kABAuthStatusNotDetermined = 0,
kABAuthStatusRestricted,
kABAuthStatusDenied,
kABAuthStatusAuthorized,
kABAuthStatusPending,
}AddressBookAuthStatus;
typedef void (^AddressbookRequestHandler)(ABAddressBookRef addressBookRef, BOOL available);
#interface AppContactsAccessManager : NSObject
{
AddressBookAuthStatus status;
}
- (void) requestAddressBookWithCompletionHandler:(AddressbookRequestHandler)handler;
- (AddressBookAuthStatus) addressBookAuthLevel;
#end
AppContactsAccessManager.m
#implementation AppContactsAccessManager
- (BOOL) isStatusAvailable:(AddressBookAuthStatus)theStatus
{
return (theStatus == kABAuthStatusAuthorized || theStatus == kABAuthStatusRestricted);
}
- (void) requestAddressBookWithCompletionHandler:(AddressbookRequestHandler)handler
{
ABAddressBookRef addressBookRef = NULL;
if([self isiOS6]){
addressBookRef = ABAddressBookCreateWithOptions(nil, nil);
ABAuthorizationStatus curStatus = ABAddressBookGetAuthorizationStatus();
if(curStatus == kABAuthorizationStatusNotDetermined)
{
status = kABAuthStatusPending;
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
status = ABAddressBookGetAuthorizationStatus();
if(handler != NULL){
handler(addressBookRef, [self isStatusAvailable:status]);
}
});
}else
{
status = curStatus;
dispatch_async(dispatch_get_current_queue(), ^{
if(handler != NULL){
handler(addressBookRef, [self isStatusAvailable:status]);
}
});
}
}else
{
addressBookRef = ABAddressBookCreate();
status = kABAuthStatusAuthorized;
dispatch_async(dispatch_get_current_queue(), ^{
if(handler != NULL){
handler(addressBookRef, [self isStatusAvailable:status]);
}
});
}
}
- (AddressBookAuthStatus) addressBookAuthLevel
{
return status;
}
#end
usage would look something like:
AppContactsAccessManager* accessMgr = [AppContactsAccessManager new];
[accessMgr requestAddressBookWithCompletionHandler:^(ABAddressBookRef theAddressBookRef, BOOL available) {
// do your addressbook stuff in here
}];

Parsing xml content tag

my problem is that i cant parse the tag from a xml file.
It returns a null value, im testing it by using an NSLog with %#.
If someone could point me a solution i would be very thankful.
Here is the code:
BOOL processed = NO;
if (currentText) {
// Remove newlines and whitespace from currentText
NSString *processedText = [currentText stringByRemovingNewLinesAndWhitespace];
// Process
switch (feedType) {
case FeedTypeRSS: {
// Item
if (!processed) {
if ([currentPath isEqualToString:#"/rss/channel/item/title"]) { if (processedText.length > 0) item.title = processedText; processed = YES; }
else if([currentPath isEqualToString:#"/rss/channel/item/url"]) { if (processedText.length > 0) item.image = processedText; processed = YES; }
else if([currentPath isEqualToString:#"/rss/channel/item/category"]) { if (processedText.length > 0) item.category = processedText; processed = YES; }
else if ([currentPath isEqualToString:#"/rss/channel/item/link"]) { if (processedText.length > 0) item.link = processedText; processed = YES; }
else if ([currentPath isEqualToString:#"/rss/channel/item/guid"]) { if (processedText.length > 0) item.identifier = processedText; processed = YES; }
else if ([currentPath isEqualToString:#"/rss/channel/item/description"]) { if (processedText.length > 0) item.summary = processedText; processed = YES; }
else if ([currentPath isEqualToString:#"/rss/channel/item/content:encoded"]) { if (processedText.length > 0) item.content = processedText; processed = YES; }
else if ([currentPath isEqualToString:#"/rss/channel/item/pubDate"]) { if (processedText.length > 0) item.date = [NSDate dateFromInternetDateTimeString:processedText formatHint:DateFormatHintRFC822]; processed = YES; }
else if ([currentPath isEqualToString:#"/rss/channel/item/enclosure"]) { [self createEnclosureFromAttributes:currentElementAttributes andAddToItem:item]; processed = YES; }
else if ([currentPath isEqualToString:#"/rss/channel/item/dc:date"]) { if (processedText.length > 0) item.date = [NSDate dateFromInternetDateTimeString:processedText formatHint:DateFormatHintRFC3339]; processed = YES; }
}
// Info
if (!processed && feedParseType != ParseTypeItemsOnly) {
if ([currentPath isEqualToString:#"/rss/channel/title"]) { if (processedText.length > 0) info.title = processedText; processed = YES; }
else if([currentPath isEqualToString:#"/rss/channel/item/url"]) { if (processedText.length > 0) item.image = processedText; processed = YES; }
else if([currentPath isEqualToString:#"/rss/channel/item/category"]) { if (processedText.length > 0) item.category = processedText; processed = YES; }
else if ([currentPath isEqualToString:#"/rss/channel/description"]) { if (processedText.length > 0) info.summary = processedText; processed = YES; }
else if ([currentPath isEqualToString:#"/rss/channel/link"]) { if (processedText.length > 0) info.link = processedText; processed = YES; }
}
break;
}
case FeedTypeRSS1: {
// Item
if (!processed) {
if ([currentPath isEqualToString:#"/rdf:RDF/item/title"]) { if (processedText.length > 0) item.title = processedText; processed = YES; }
else if([currentPath isEqualToString:#"/rss/channel/item/url"]) { if (processedText.length > 0) item.image = processedText; processed = YES; }
else if([currentPath isEqualToString:#"/rss/channel/item/category"]) { if (processedText.length > 0) item.category = processedText; processed = YES; }
else if ([currentPath isEqualToString:#"/rdf:RDF/item/link"]) { if (processedText.length > 0) item.link = processedText; processed = YES; }
else if ([currentPath isEqualToString:#"/rdf:RDF/item/dc:identifier"]) { if (processedText.length > 0) item.identifier = processedText; processed = YES; }
else if ([currentPath isEqualToString:#"/rdf:RDF/item/description"]) { if (processedText.length > 0) item.summary = processedText; processed = YES; }
else if ([currentPath isEqualToString:#"/rdf:RDF/item/content:encoded"]) { if (processedText.length > 0) item.content = processedText; processed = YES; }
else if ([currentPath isEqualToString:#"/rdf:RDF/item/dc:date"]) { if (processedText.length > 0) item.date = [NSDate dateFromInternetDateTimeString:processedText formatHint:DateFormatHintRFC3339]; processed = YES; }
else if ([currentPath isEqualToString:#"/rdf:RDF/item/enc:enclosure"]) { [self createEnclosureFromAttributes:currentElementAttributes andAddToItem:item]; processed = YES; }
}
call method:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell.
MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];
if (item) {
NSLog(#"content = %#",item.content);//<-------------------------------------------Returns a NULL
// Process
NSString *itemTitle = item.title ? [item.title stringByConvertingHTMLToPlainText] : #"[No Title]";
NSString *itemSummary = item.summary ? [item.summary stringByConvertingHTMLToPlainText] : #"[No Summary]";
// Set
cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
cell.textLabel.text = itemTitle;
NSMutableString *subtitle = [NSMutableString string];
if (item.date) [subtitle appendFormat:#"%#: ", [formatter stringFromDate:item.date]];
[subtitle appendString:itemSummary];
cell.detailTextLabel.text = subtitle;
}
return cell;
}
Best Regards
While parsing every element the parser will return a whitespace character as a response because of new line / tabbing / carriage returns. If you have implemented a call back methods (delegates) of parser then check for null values, and i donno where you have implemented(in the sense,in which parser delegate method has this) the very first snippet.

Move Cursor One Word at a Time in UTextView

I would like to create a button that moves the cursor position in a UITextView one word at a time. From a user perspective, this would be the same as Option-Right Arrow in Mac OS X, which is defined as "go to the word to the right of the insertion point."
I have found a couple ways to move on character at a time. How would you modify this to move one word at a time?
- (IBAction)rightArrowButtonPressed:(id)sender
{
myTextView.selectedRange = NSMakeRange(myTextView.selectedRange.location + 1, 0);
}
Thanks for any suggestions.
Was able to implement it like this,
- (IBAction)nextWord {
NSRange selectedRange = self.textView.selectedRange;
NSInteger currentLocation = selectedRange.location + selectedRange.length;
NSInteger textLength = [self.textView.text length];
if ( currentLocation == textLength ) {
return;
}
NSRange newRange = [self.textView.text rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]
options:NSCaseInsensitiveSearch
range:NSMakeRange((currentLocation + 1), (textLength - 1 - currentLocation))];
if ( newRange.location != NSNotFound ) {
self.textView.selectedRange = NSMakeRange(newRange.location, 0);
} else {
self.textView.selectedRange = NSMakeRange(textLength, 0);
}
}
- (IBAction)previousWord {
NSRange selectedRange = self.textView.selectedRange;
NSInteger currentLocation = selectedRange.location;
if ( currentLocation == 0 ) {
return;
}
NSRange newRange = [self.textView.text rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]
options:NSBackwardsSearch
range:NSMakeRange(0, (currentLocation - 1))];
if ( newRange.location != NSNotFound ) {
self.textView.selectedRange = NSMakeRange((newRange.location + 1), 0);
} else {
self.textView.selectedRange = NSMakeRange(0, 0);
}
}

How to only add an object to my array when it fulfills certain requirements

I'm developing a Twitter app and I'm having problems with adding tweets to an NSArray. The problem is I get the tweets, and all the content ok, but the last query i got is just for control, so it doesn't contains the object "tweet" (which is the tweet content). I have tried stopping it if it detects the control query but no luck. This is the normal search query:
See dictionary: {
"created_at" = 1305363612;
"from_user" = IamDeShayDenise;
"from_user_id" = 123375840;
"from_user_id_str" = 123375840;
geo = "";
id = 69326131068813312;
"id_str" = 69326131068813312;
"iso_language_code" = en;
metadata = {
"result_type" = recent;
};
"profile_image_url" = "http://a3.twimg.com/profile_images/1336852311/110302-003005_normal.jpg";
source = "web";
"source_api_request_type" = 33;
text = "#LondonBlackk Yeah....and Yes I was With My Mommy and Nana!!! && Still Pulling All The Guys...LoL";
"to_user" = LondonBlackk;
"to_user_id" = 172117314;
"to_user_id_str" = 172117314;
}
In that one I get the text object ok and I can read it. The problem comes when I get this:
See dictionary: {
"source_api_request_type" = 33;
}
Or this:
See dictionary: {
"completed_in" = "0.027116";
"max_id" = 69324964586725376;
"max_id_str" = 69324964586725376;
"next_page" = "?page=2&max_id=69324964586725376&q=lol";
page = 1;
query = lol;
"refresh_url" = "?since_id=69324964586725376&q=lol";
"results_per_page" = 15;
"since_id" = 1;
"since_id_str" = 1;
"source_api_request_type" = 33;
warning = "since_id removed for pagination.";
}
And this is the code I use for filling the arrays:
tweets = [[NSMutableArray alloc] init];
usernames = [[NSMutableArray alloc] init];
for(NSDictionary *d in searchResults) {
NSLog(#"See dictionary: %#", d);
Tweet *author = [d objectForKey:#"from_user"];
Tweet *tweet = [d objectForKey:#"text"];
if ([d objectForKey:#"from_user"] == nil || [d objectForKey:#"text"] == nil){
NSLog(#"end");
}
[usernames addObject:author];
[tweets addObject:tweet];
[author release];
[tweet release];
}
I don't know what can be wrong :(
Thanks in advance :D
*UPDATE:*Got it working in this way
if ([d objectForKey:#"from_user"] == nil || [d objectForKey:#"text"] == nil){
NSLog(#"end");
} else {
[usernames addObject:author];
[tweets addObject:tweet];
}
instead of:
if ([d objectForKey:#"from_user"] == nil || [d objectForKey:#"text"] == nil){
NSLog(#"end");
}
[usernames addObject:author];
[tweets addObject:tweet];
Then the other problem was also solved. Thanks y'all!!
The way of solving it is this:
if ([d objectForKey:#"from_user"] == nil || [d objectForKey:#"text"] == nil){
NSLog(#"end");
} else {
[usernames addObject:author];
[tweets addObject:tweet];
}
instead of:
if ([d objectForKey:#"from_user"] == nil || [d objectForKey:#"text"] == nil){
NSLog(#"end");
}
[usernames addObject:author];
[tweets addObject:tweet];