-JSONValue Failed error trace is:Garbage after JSON - iphone

I am using Json Parsing with autosuggestion
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
autoCompleteTable.hidden = NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
if(substring.length>=3)
{
[self getDescriptionData];
[self searchAutocompleteEntriesWithSubstring:substring];
}
else {
[placesArray removeAllObjects];
[autoCompleteTable reloadData];
}
return YES;
}
JSON value is retrieved in getDescription method. but when it is called second tine i am getting error:
-JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=10 \"Garbage after JSON\" UserInfo=0x4b60160 {NSLocalizedDescription=Garbage after JSON}"
)

i met the same thing.
After googling and stackflowing, i found nothing.
so i decide to use JSONKit instead:
(github: https://github.com/johnezang/JSONKit)
// sbjson
// NSString *jsonStr = [NSString stringWithCString:[receivedData bytes]
// encoding:NSUTF8StringEncoding];
// NSArray *returnArr = [jsonStr JSONValue];
// jsonkit
JSONDecoder *decoder = [JSONDecoder decoder];
NSError *error;
NSArray *returnArr = [decoder objectWithData:receivedData error:&error];
Finally, this works.

Related

Local search in NSMutalbleArray

I want to search in NSMutalbleArray, my code is :
arrCelebs=[[NSMutableArray alloc] initWithObjects:#"Test 1",#"Test 2",#"Test 42",#"Test 5", nil];
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *arrString1 = txtSearch.text;
NSRange tmprange;
for(NSString *string in arrCelebs) {
tmprange = [arrString1 rangeOfString:string];
if (tmprange.location != NSNotFound) {
NSLog(#"String found");
break;
}
}
return YES;
}
if i enter "t" then it search all the data and i want to add it another array. for display in tableview.
You can use the power of NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF BEGINSWITH[c] %#", textField.text];
NSArray *filteredArray = [arrCelebs filteredArrayUsingPredicate:predicate];
By using predicate you Can easily get the result efficiently.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", txtSearch.text];
NSArray *ResultArray = [yourArray filteredArrayUsingPredicate:predicate];
return YES;
}
Try :
arr_NewArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [arr_YourArrayToSearch count]; i++)
{
NSString *curString = [string lowercaseString];
NSString *curStringInArray = [[arr_YourArrayToSearch objectAtIndex:i]lowercaseString];
if (![curString rangeOfString:curStringSmall].location == NSNotFound)
{
[arr_NewArray addObject:[arr_YourArrayToSearch objectAtIndex:i]];
}
}
arr_NewArray will give you the array with data matched to your search string.
arrCelebs=[[NSMutableArray alloc] initWithObjects:#"Test 1",#"Test 2",#"Test 42",#"Test 5", nil];
_resultArray = [[NSMutableArray alloc] init];
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *arrString1 = txtSearch.text;
NSRange tmprange;
_resultArray = [[NSMutableArray alloc] init];
for(NSString *string in arrCelebs) {
tmprange = [arrString1 rangeOfString:string];
if (tmprange.location != NSNotFound) {
[_resultArray addObject:string];
}
}
return YES;
}
IF YOU work With UITableView then you cal also put this type of Logic.
Take Two NSMutableArray and add one array to another array in ViewDidLoad method such like,
self.listOfTemArray = [[NSMutableArray alloc] init]; // array no - 1
self.ItemOfMainArray = [[NSMutableArray alloc] initWithObjects:#"YorArrayList", nil]; // array no - 2
[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray]; // add 2array to 1 array
And Write following delegate Method of UISearchBar
- (BOOL) textFieldDidChange:(UITextField *)textField
{
NSString *name = #"";
NSString *firstLetter = #"";
if (self.listOfTemArray.count > 0)
[self.listOfTemArray removeAllObjects];
if ([searchText length] > 0)
{
for (int i = 0; i < [self.ItemOfMainArray count] ; i = i+1)
{
name = [self.ItemOfMainArray objectAtIndex:i];
if (name.length >= searchText.length)
{
firstLetter = [name substringWithRange:NSMakeRange(0, [searchText length])];
//NSLog(#"%#",firstLetter);
if( [firstLetter caseInsensitiveCompare:searchText] == NSOrderedSame )
{
// strings are equal except for possibly case
[self.listOfTemArray addObject: [self.ItemOfMainArray objectAtIndex:i]];
NSLog(#"=========> %#",self.listOfTemArray);
}
}
}
}
else
{
[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray ];
}
[self.tblView reloadData];
}
}
Output Show in your Consol.
This exact what you want...
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSMutableArray *resultAry = [[NSMutableArray alloc] init];
for(NSString *string in arrCelebs)
{
NSRange range = [string rangeOfString:textField.text options:NSCaseInsensitiveSearch];
if(range.location != NSNotFound)
{
[resultAry addObject:string];
}
}
yourTableAry=[resultAry mutableCopy];
[yourTable reloadData];
return YES;
}

NSLog shows NSString correctly - Trying to show the string on a label crashes the app (unrecognized selector)

App crashes when trying to update an UILabel with a NSString.
Showing the same NSString on console works.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (self.connectionData)
{
NSError *error;
self.dict = [NSJSONSerialization JSONObjectWithData:self.connectionData options:kNilOptions error:&error];
self.matchesArray = self.dict[#"matches"];
NSString *title = [self.matchesArray valueForKey:#"title"];
NSLog(#"NSString TITLE contains: %#", title);
self.titleLabel.text = title;
}
}
CONSOLE OUTPUT:
2013-01-16 13:54:08.550 ZEITreisen[3168:c07] NSString TITLE contains: (
"Mark und Dollar"
)
2013-01-16 13:54:08.552 ZEITreisen[3168:c07] -[__NSArrayI isEqualToString:]: unrecognized selector sent to instance 0xde93850
(lldb)
title is not NSString, it is NSArray
so
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (self.connectionData)
{
NSError *error;
self.dict = [NSJSONSerialization JSONObjectWithData:self.connectionData options:kNilOptions error:&error];
self.matchesArray = self.dict[#"matches"];
NSArray *title = [self.matchesArray valueForKey:#"title"];
NSLog(#"NSString TITLE contains: %#", title);
self.titleLabel.text = [title lastObject];
}
}
Try :
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (self.connectionData)
{
NSError *error;
self.dict = [NSJSONSerialization JSONObjectWithData:self.connectionData options:kNilOptions error:&error];
self.matchesArray = self.dict[#"matches"];
NSString *title = [self.matchesArray valueForKey:#"title"];
NSLog(#"NSString TITLE contains: %#", title);
self.titleLabel.text = [NSString stringWithFormat:#"%#",[title objectAtIndex:0]];
}
}
maybe the values you stored in self.matchesArray is not a string

Regular expression for US phone number not working

This type of questions are asked so many times on SO but i am having problem with expression and its not working for me.
I need to allow only numbers,(,),- in phone number and for that i have code as follows.
But only uncommented expression is working and that is for only numbers no (,),- are allowed and i searched and got other expressions which should allow (,),- but those are not working too.
What could be wrong?
Example: 9876545678, (123) 123-7657
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([string isEqualToString:#""]) {
return TRUE;
}
if(textField == aTfdPhone)
{
if ([string isEqualToString:#"."]) {
return NO;
}
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *expression = #"^([0-9]+)?(\\.([0-9])?)?$";
// NSString *expression = #"^[(]?[2-9][0-9]{2}[)]?[ -]?[0-9]{3}[ -]?[0-9]{4}$";
// NSString * const expression = #"^([+-]{1})([0-9]{3})$";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:&error];
if (error) {
NSLog(#"error %#", error);
}
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0
range:NSMakeRange(0, [newString length])];
if (numberOfMatches == 0){
return NO;
}
}
return TRUE;
}
Your second attempt fails to recognize (123) 123-7657 because of the first digit:
It should be
NSString *expression = #"^[(]?[1-9][0-9]{2}[)]?[ -]?[0-9]{3}[ -]?[0-9]{4}$";
not
NSString *expression = #"^[(]?[2-9][0-9]{2}[)]?[ -]?[0-9]{3}[ -]?[0-9]{4}$";
The only difference is the operator matching the first digit [2-9] would not match 1.

xcode 4.2.1 - limiting character length in TextField

I have been trying to limit a textField by many codes available out there in the internet but with no luck.
I have added UIViewController<UITextFieldDelegate> in my header file
and textField.delegate = self; in my viewDidLoad
and implemented the following fundtion in my .m file:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return !([newString length] > 5);
}
this stil does not limit my text field. any idea?
Do it as following as it has been the exact duplicate of this
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 5) ? NO : YES;
}
The replacement string is just the 1 character that was pressed, not the whole string so you need to add It to the current textfield.text before counting.
Your count is probably always 1 (or more if pasting a word)
I implement this in my code and it works:
This code eliminate all the letters only accept numbers, but like I delete the character, you could delete everything that its over length 5 and it keeps a nice effect that appears and disappears
- (void)textFieldDidBeginEditing:(UITextField *)textField {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(textChanged:) name:UITextFieldTextDidChangeNotification object:textField];
}
- (void)textChanged:(NSNotification *)textField {
NSString *text = [[textField object] text];
NSString *last = [text substringFromIndex:[text length] -1];
NSArray *accept = [NSArray arrayWithObjects:#"0", #"1", #"2", #"3", #"4", #"5", #"6", #"7" , #"8", #"9", #".", nil];
for (int i=0; i<[accept count]; i++) {
NSLog(#"%#", [accept objectAtIndex:i]);
if (![last isEqualToString:[accept objectAtIndex:i]]) {
[[textField object] setText:[text substringToIndex:[text length]-1]];
}
}
}

stringWithContentsOfUrl failing after updating to OS3.1

I have an application which has been running happily, but since I updated to OS3.1 and updated the SDK the application is failing to log onto a remote server, passing a connection string to the stringWithContentsOfUrl function.
Before the update this was working fine, and if I copy the text string which is displayed on the NSLog statement and paste that into a browser, then I get the correct response, however, this is replying with "LOGIN_ERROR" indicating failure.
Any idea why this is now failing and how to fix it?
NSString* userName = [[NSUserDefaults standardUserDefaults] stringForKey:#"username_pref"];
NSString* password = [[NSUserDefaults standardUserDefaults] stringForKey:#"password_pref"];
NSString* loginUrl = [NSString stringWithFormat:#"https://website.com/API/login?email=%#&password=%#", userName, password];
NSLog (#"Logging in as %# using %# at [%#]", userName, password, loginUrl);
NSURL* url = [NSURL URLWithString:loginUrl];
NSString* loginDetails = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
if ([loginDetails compare:#"\"LOGIN_ERROR\""] == NSOrderedSame)
{
DLog (#"Login Failed : LOGIN_ERROR");
self.isLoggedIn = NO;
}
else
{
DLog (#"Login Success");
if (userDetails) {
[userDetails release];
}
NSDictionary* jsonData = [loginDetails JSONValue];
userDetails = [[[DMUserDetails alloc] init] retain];
userDetails.id = [[jsonData objectForKey:#"id"] intValue];
userDetails.api_token = [jsonData objectForKey:#"api_token"];
userDetails.full_name = [jsonData objectForKey:#"full_name"];
userDetails.mobile_number = [jsonData objectForKey:#"mobile_number"];
userDetails.mobile_host = [jsonData objectForKey:#"mobile_host"];
userDetails.email = [jsonData objectForKey:#"email"];
userDetails.twitter = [jsonData objectForKey:#"twitter"];
userDetails.jabber = [jsonData objectForKey:#"jabber"];
userDetails.msn = [jsonData objectForKey:#"msn"];
userDetails.start_page = [jsonData objectForKey:#"start_page"];
userDetails.date_format = [[jsonData objectForKey:#"date_format"] intValue];
userDetails.time_format = [[jsonData objectForKey:#"time_format"] intValue];
userDetails.sort_order = [[jsonData objectForKey:#"sort_order"] intValue];
userDetails.timezone = [jsonData objectForKey:#"timezone"];
userDetails.tz_offset = [jsonData objectForKey:#"tz_offset"];
userDetails.premium_until = [jsonData objectForKey:#"premium_until"];
userDetails.default_reminder = [jsonData objectForKey:#"default_reminder"];
self.isLoggedIn = YES;
}
[self performSelectorOnMainThread:#selector(didFinishLogon) withObject:nil waitUntilDone:NO];
If your user name is an e-mail address and has an at sign (#) in it, have you tried to escape the at sign in the URL by using %40 instead of #?
The most likely problem is that loginDetails is nil, indicating an error retrieving the URL, rather than you actually receiving a "LOGIN ERROR" response.
Pass in an error object and log the error.
Try:
NSError *error = nil;
NSString *loginDetails = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
if (error != nil) {
NSLog(#"%#", error);
}