Getting called only on first three numbers - ios

I am getting phone numbers in format (888) 478-0041. And I am creating a link for that means if you tap on that phone number, it will automatically make a call. But in this format my call is going only on first three numbers is (888). so what should I do, I am not getting.
I have an string which is coming from a server :
<p>Your 2017 F-150 may need an oil change soon. Call </p><b>(888) 853-6045</b><p> or (888) 478-0041 click</p><b> here</b><p> to schedule online. Jacob Williams, Service Manager</p>
I want to remove any space after tel which comes up to 10 characters in the phone number.
I am using the below code for that.
if ([serviceMessage containsString:#"tel:"]) {
NSUInteger location = [serviceMessage rangeOfString:#"tel:"].location + 4;
serviceMessage = [serviceMessage substringFromIndex:location];
[serviceMessage substringWithRange:NSMakeRange(11,0)];
serviceMessage =[serviceMessage substringToIndex:10];
NSLog(#"New Trimmed string:%#",serviceMessage);
serviceMessage = [serviceMessage stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"Final Trimmed string:%#",serviceMessage);
}

You need to use replaceOccurrencesOfString:withString:options:range: if you just want to replace space within specific range and for multiple searching of tel: use NSRegularExpression.
NSString *serviceMessage = #"<p>Your 2017 F-150 may need an oil change soon. Call </p><b>(888) 853-6045</b><p> or (888) 478-0041 click</p><b> here</b><p> to schedule online. Jacob Williams, Service Manager</p>";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"(tel:)" options:0 error:&error];
NSArray *matches = [regex matchesInString:serviceMessage options:0 range:NSMakeRange(0, serviceMessage.length)];
for (NSTextCheckingResult *match in matches) {
NSRange wordRange = [match rangeAtIndex:1];
NSUInteger location = wordRange.location + 4;
serviceMessage = [serviceMessage stringByReplacingOccurrencesOfString:#" " withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(location, 13)];
}
NSLog(#"%#",serviceMessage);
Output
<p>Your 2017 F-150 may need an oil change soon. Call </p><b>(888) 853-6045</b><p> or (888) 478-0041 click</p><b> here</b><p> to schedule online. Jacob Williams, Service Manager</p>

"Mr. Aditya Pandey" have given a very nice and techfull solution. But if you are not more familiar with the iOS concepts and if you find that solution hard, you can also go with the option below:
if ([responceStr containsString:#"tel:"]) {
NSUInteger location = [responceStr rangeOfString:#"tel:"].location;
NSString *subStr = [responceStr substringFromIndex:location];
NSString *endStr;
if ([subStr containsString:#"\">"])
{
NSUInteger endLocation = [subStr rangeOfString:#"\">"].location;
endStr = [subStr substringToIndex:endLocation];
}
NSLog(#"New Trimed string:%#",endStr);
responceStr = [endStr stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"Final Trimed string:%#",responceStr);
}
You can again start searching for the next tel: from endStr.

Related

How to add a character at start and end of every word in NSString

Suppose i have this:
NSString *temp=#"its me";
Now suppose i want ' " ' in start and end of every word, how can i achieve it to get the result like this:
"its" "me"
Do i have to use regular expressions?
If you have punctuation inside the string, splitting with a space might not be enough.
Use the word boundary \b: it matches both the leading and trailing word boundaries (that is, it will match an empty space right between word and non-word characters and also at the start/end of the string if followed/preceded with a word character.
NSError *error = nil;
NSString *myText = #"its me";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\b" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate:#"\""];
NSLog(#"%#", modifiedString); // => "its" "me"
See the IDEONE demo
See more details on the regex syntax in Objective C here.
You can do something like,
NSString *str = #"its me";
NSMutableString *resultStr = [[NSMutableString alloc]init];
NSArray *arr = [str componentsSeparatedByString:#" "];
for (int i = 0; i < arr.count; i++) {
NSString *tempStr = [NSString stringWithFormat:#"\"%#\"",arr[i]];
resultStr = [resultStr stringByAppendingString:[NSString stringWithFormat:#"%# ",tempStr]];
}
NSLog(#"result string is : %#",resultStr);
Hope this will help :)

Is it possible to detect links within an NSString that have spaces in them with NSDataDetector?

First off, I have no control over the text I am getting. Just wanted to put that out there so you know that I can't change the links.
The text I am trying to find links in using NSDataDetector contains the following:
<h1>My main item</h1>
<img src="http://www.blah.com/My First Image Here.jpg">
<h2>Some extra data</h2>
The detection code I am using is this, but it will not find this link:
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:myHTML options:0 range:NSMakeRange(0, [myHTML length])];
for (NSTextCheckingResult *match in matches)
{
if ([match resultType] == NSTextCheckingTypeLink)
{
NSURL *url = [match URL];
// does some stuff
}
}
Is this a bug with Apple's link detection here, where it can't detect links with spaces, or am I doing something wrong?
Does anyone have a more reliable way to detect links regardless of whether they have spaces or special characters or whatever in them?
I just got this response from Apple for a bug I filed on this:
We believe this issue has been addressed in the latest iOS 9 beta.
This is a pre-release iOS 9 update.
Please refer to the release notes for complete installation
instructions.
Please test with this release. If you still have issues, please
provide any relevant logs or information that could help us
investigate.
iOS 9 https://developer.apple.com/ios/download/
I will test and let you all know if this is fixed with iOS 9.
You could split the strings into pieces using the spaces so that you have an array of strings with no spaces. Then you could feed each of those strings into your data detector.
// assume str = <img src="http://www.blah.com/My First Image Here.jpg">
NSArray *components = [str componentsSeparatedByString:#" "];
for (NSString *strWithNoSpace in components) {
// feed strings into data detector
}
Another alternative is to look specifically for that HTML tag. This is a less generic solution, though.
// assume that those 3 HTML strings are in a string array called strArray
for (NSString *htmlLine in strArray) {
if ([[htmlLine substringWithRange:NSMakeRange(0, 8)] isEqualToString:#"<img src"]) {
// Get the url from the img src tag
NSString *urlString = [htmlLine substringWithRange:NSMakeRange(10, htmlLine.length - 12)];
}
}
I've found a very hacky way to solve my issue. If someone comes up with a better solution that can be applied to all URLs, please do so.
Because I only care about URLs ending in .jpg that have this problem, I was able to come up with a narrow way to track this down.
Essentially, I break out the string into components based off of them beginning with "http:// into an array. Then I loop through that array doing another break out looking for .jpg">. The count of the inner array will only be > 1 when the .jpg"> string is found. I then keep both the string I find, and the string I fix with %20 replacements, and use them to do a final string replacement on the original string.
It's not perfect and probably inefficient, but it gets the job done for what I need.
- (NSString *)replaceSpacesInJpegURLs:(NSString *)htmlString
{
NSString *newString = htmlString;
NSArray *array = [htmlString componentsSeparatedByString:#"\"http://"];
for (NSString *str in array)
{
NSArray *array2 = [str componentsSeparatedByString:#".jpg\""];
if ([array2 count] > 1)
{
NSString *stringToFix = [array2 objectAtIndex:0];
NSString *fixedString = [stringToFix stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
newString = [newString stringByReplacingOccurrencesOfString:stringToFix withString:fixedString];
}
}
return newString;
}
You can use NSRegularExpression to fix all URLs by using a simple regex to detect the links and then just encode the spaces (if you need more complex encoding you can look into CFURLCreateStringByAddingPercentEscapes and there are plenty of examples out there). The only thing that might take you some time if you haven't worked with NSRegularExpression before is how to iterate the results and do the replacing, the following code should do the trick:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"src=\".*\"" options:NSRegularExpressionCaseInsensitive error:&error];
if (!error)
{
NSInteger offset = 0;
NSArray *matches = [regex matchesInString:myHTML options:0 range:NSMakeRange(0, [myHTML length])];
for (NSTextCheckingResult *result in matches)
{
NSRange resultRange = [result range];
resultRange.location += offset;
NSString *match = [regex replacementStringForResult:result inString:myHTML offset:offset template:#"$0"];
NSString *replacement = [match stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
myHTML = [myHTML stringByReplacingCharactersInRange:resultRange withString:replacement];
offset += ([replacement length] - resultRange.length);
}
}
Try this regex pattern: #"<img[^>]+src=(\"|')([^\"']+)(\"|')[^>]*>" with ignore case ... Match index=2 for source url.
regex demo in javascript: (Try for any help)
Demo
Give this snippet a try (I got the regexp from your first commentator user3584460) :
NSError *error = NULL;
NSString *myHTML = #"<http><h1>My main item</h1><img src=\"http://www.blah.com/My First Image Here.jpg\"><h2>Some extra data</h2><img src=\"http://www.bloh.com/My Second Image Here.jpg\"><h3>Some extra data</h3><img src=\"http://www.bluh.com/My Third-Image Here.jpg\"></http>";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"src=[\"'](.+?)[\"'].*?>" options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *arrayOfAllMatches = [regex matchesInString:myHTML options:0 range:NSMakeRange(0, [myHTML length])];
NSTextCheckingResult *match = [regex firstMatchInString:myHTML options:0 range:NSMakeRange(0, myHTML.length)];
for (NSTextCheckingResult *match in arrayOfAllMatches) {
NSRange range = [match rangeAtIndex:1];
NSString* substringForMatch = [myHTML substringWithRange:range];
NSLog(#"Extracted URL : %#",substringForMatch);
}
In my log, I have :
Extracted URL : http://www.blah.com/My First Image Here.jpg
Extracted URL : http://www.bloh.com/My Second Image Here.jpg
Extracted URL : http://www.bluh.com/My Third-Image Here.jpg
You should not use NSDataDetector with HTML. It is intended for parsing normal text (entered by an user), not computer-generated data (in fact, it has many heuristics to actually make sure it does not detect computer-generated things which are probably not relevant to the user).
If your string is HTML, then you should use an HTML parsing library. There are a number of open-source kits to help you do that. Then just grab the href attributes of your anchors, or run NSDataDetector on the text nodes to find things not marked up without polluting the string with tags.
URLs really shouldn't contain spaces. I'd remove all spaces from the string before doing anything URL-related with it, something like the following
// Custom function which cleans up strings ready to be used for URLs
func cleanStringForURL(string: NSString) -> NSString {
var temp = string
var clean = string.stringByReplacingOccurrencesOfString(" ", withString: "")
return clean
}

I want to remove static text from string - iOS

Hi I have a News Reader and I keep getting a string like this -
two New York police officers shot dead in 'ambush'
I want the string two New York police officers shot dead in ambush
How can I scan from & to ; and then delete occurrences of the scan.
I created a scanner like so -
NSString *webString222222 = filteredTitle2;
NSScanner *stringScanner222222 = [NSScanner scannerWithString:webString222222];
NSString *content222222 = [[NSString alloc] init];
[stringScanner222222 scanUpToString:#"&" intoString:Nil];
[stringScanner222222 scanUpToString:#";" intoString:&content222222];
NSString *filteredTitle222 = [content222222 stringByReplacingOccurrencesOfString:content222222 withString:#""];
NSString *filteredTitle22 = [filteredTitle222 stringByReplacingOccurrencesOfString:#"&" withString:#""];
But when I do this code the whole text disappears! Every single word.
When I check the title in my NSLog that is the only & sign in there and the only ; sign in there!
Im not sure where I went wrong here.
If the special characters you are encountering are all relatively consistent you can merely replace each of those substrings with the empty string, like so:
NSString *cleansedString = [filteredTitle2 stringByReplacingOccurrencesOfString:#"'"
withString:#""];
You can use NSRegularExpression to build proper matching pattern:
NSString *pattern = #"\\&#[0-9]+;";
NSString *str = #"two New York police officers shot dead in 'ambush'";
NSLog(#"Original test: %#",str);
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive error:&error];
if (error != nil)
{
NSLog(#"ERror: %#",error);
}
else
{
NSString *replaced = [regex stringByReplacingMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:#""];
NSLog(#"Replaced test: %#",replaced);
}
See https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSRegularExpression_Class/index.html

How properly extract substrings from an NSString without hardcoding positions?

I have this string returning:
"Monday thru Friday 8:00 AM - 7:30 PM"
I need to eliminate the mon-fri stuff in order to get this:
"8:00AM - 7:30PM"
And then I need to split it into opening time and closing time in order to determine if its open or not:
"8:00AM" && "7:30PM"
But there are a lot of stores and they have different opening and closing times, so I cant just extract 6 characters from 8 or anything like that.
So far I decided to go this route:
NSRange startRange = [storeTime.text rangeOfString:#"-"];
NSString *openString = [storeTime.text substringWithRange:NSMakeRange(16, startRange.location-17)];
NSString *closeString = [storeTime.text substringWithRange:NSMakeRange(startRange.location+2, storeTime.text.length-(startRange.location+2))];
But it just seems like i could break because of the hardcoded start at 16 and it makes me wonder if it could break anywhere else. Any better ideas on how to achieve this?
You can use NSRegularExpression to grab the two time strings out of a string:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\\d{1,2}:\\d{2} (AM|PM)"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *str = #"Monday thru Friday 8:00 AM - 7:30 PM";
NSArray *m = [regex matchesInString:str
options:0
range:NSMakeRange(0, str.length)];
If you know the text before the time interval is always in the format <someday> thru <someday>, then you can find the index of the first numerical character (digit), and get a substring from that index.
Then, split the time strings on #" - " using the componentsSeparatedByString: method.
Example:
NSString *s = #"monday thru sunday, 0:00 - 23:59";
NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
int idx = [s rangeOfChatacterFromSet:digits].location;
NSString *timeStr = [s substringFromIndex:idx];
NSArray *timeStrings = [timeStr componentsSeparatedByString:#" - "];
How about first go by replacing occurrences of some strings.
So use the [string stringByReplacingOccurrencesOfString:#"Monday" withString: #""];
remove all the days and probably the "thru" string.
Then you're left with the hours. Don't forget to watch for space characters.
Hope this helps.

Finding first letter in NSString and counting backwards

I'm new to IOS, and was looking for some guidance.
I have a long NSString that I'm parsing out. The beginning may have a few characters of garbage (can be any non-letter character) then 11 digits or spaces, then a single letter (A-Z). I need to get the location of the letter, and get the substring that is 11 characters behind the letter to 1 character behind the letter.
Can anyone give me some guidance on how to do that?
Example: '!!2553072 C'
and I want : '53072 '
You can accomplish this with the regex pattern: (.{11})\b[A-Z]\b
The (.{11}) will grab any 11 characters and the \b[A-Z]\b will look for a single character on a word boundary, meaning it will be surrounded by spaces or at the end of the string. If characters can follow the C in your example then remove the last \b. This can be accomplished in Objective-C like so:
NSError *error;
NSString *example = #"!!2553072 C";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(.{11})\\b[A-Z]\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
if(!regex)
{
//handle error
}
NSTextCheckingResult *match = [regex firstMatchInString:example
options:0
range:NSMakeRange(0, [example length])];
if(match)
{
NSLog(#"match: %#", [example substringWithRange:[match rangeAtIndex:1]]);
}
There may be a more elegant way to do this involving regular expressions or some Objective-C wizardry, but here's a straightforward solution (personally tested).
-(NSString *)getStringContent:(NSString *)input
{
NSString *substr = nil;
NSRange singleLetter = [input rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if(singleLetter.location != NSNotFound)
{
NSInteger startIndex = singleLetter.location - 11;
NSRange substringRange = NSMakeRange(start, 11);
substr = [tester substringWithRange:substringRange];
}
return substr;
}
You can use NSCharacterSets to split up the string, then take the first remaining component (consisting of your garbage and digits) and get a substring of that. For example (not compiled, not tested):
- (NSString *)parseString:(NSString *)myString {
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
NSArray *components = [myString componentsSeparatedByCharactersInSet:letters];
assert(components.count > 0);
NSString *prefix = components[0]; // assuming relatively new Xcode
return [prefix substringFromIndex:(prefix.length - 11)];
}
//to get rid of all non-Digits in a NSString
NSString *customerphone = CustomerPhone.text;
int phonelength = [customerphone length];
NSRange customersearchRange = NSMakeRange(0, phonelength);
for (int i =0; i < phonelength;i++)
{
const unichar c = [customerphone characterAtIndex:i];
NSString* onechar = [NSString stringWithCharacters:&c length:1];
if(!isdigit(c))
{
customerphone = [customerphone stringByReplacingOccurrencesOfString:onechar withString:#"*" options:0 range:customersearchRange];
}
}
NSString *PhoneAllNumbers = [customerphone stringByReplacingOccurrencesOfString:#"*" withString:#"" options:0 range:customersearchRange];

Resources