Replace lines of text in iOS - ios

I am needing to replace a line of text in code on my iOS app, however the lines that need to be replaced in the particular NSString will be different for different entries on the XML that is being parsed.
For example, I need to replace 129727-the-cave.mp3 with 129727.jpg.
However, I can't just tell it to replace -the-cave.mp3, because some instances of the string will have a different number and title of mp3. I think the next line is:
129838-my-song.mp3.
So, basically, I need a way to find everything from the first hyphen through mp3 and replace it, no matter what the text is?

Try this:
NSString *original = #"129727-the-cave.mp3";
NSString *sub = [original substringToIndex:[original rangeOfString:#"-"].location];
NSString *finalString = [sub stringByAppendingString:#".jpg"];
NSLog(#"finalString: %#", finalString);

Related

"ԅ" causing iOS app crash

I find that if I set UILabel's text to "ԅ", it crashes without further information. It didn't hit the "All Exception" breakpoint.
self.label.text = #"ԅԅ";
How do I get rid of this crash? Thank you in advance!
By the way, I found this problem due to an emoticon "ԅ(¯﹃¯ԅ)", which kind of describes what I'm feeling right now.
Do not pass directly a Unicode character to NSString initialisation, instead use the character's Unicode code-point representation. In case of this character, it'd be #"\u504".
try this:
NSData *strd = [text dataUsingEncoding:NSUTF16StringEncoding];
NSString *newStr = [[NSString alloc] initWithData:strd encoding:NSUTF16StringEncoding];

Share image in iMessage using Custom Keyboard in iOS 8

I am working on iOS 8 custom keyboard, where i have designed keyboard using some images like smiley. i want this keyboard to be work with iMessage. when i am trying to send text its working properly but can't able to share image there. I have tried following code :
To share text : (its working properly)
-(void)shouldAddCharector:(NSString*)Charector{
if ([Charector isEqualToString:#"Clear"]) {
[self.textDocumentProxy deleteBackward];
} else if([Charector isEqualToString:#"Dismiss"]){
[self dismissKeyboard];
} else {
[self.textDocumentProxy insertText:Charector];
}
}
To add image : ( Not working)
-(void)shouldAddImage:(UIImage*)oneImage
{
UIImage* onions = [UIImage imageNamed:#"0.png"];
NSMutableAttributedString *mas;
NSTextAttachment* onionatt = [NSTextAttachment new];
onionatt.image = onions;
onionatt.bounds = CGRectMake(0,-5,onions.size.width,onions.size.height);
NSAttributedString* onionattchar = [NSAttributedString attributedStringWithAttachment:onionatt];
NSRange r = [[mas string] rangeOfString:#"Onions"];
[mas insertAttributedString:onionattchar atIndex:(r.location + r.length)];
NSString *string =[NSString stringWithFormat:#"%#",mas];
[self.textDocumentProxy insertText:string];
}
Is there any possibility to pass image to [self.textDocumentProxy insertText:string];
following attached image shows how exactly i want to use this image keyboard. i am surprised how emoji keyboard will work?
As far as I know, the behavior you are looking for is not possible as of iOS 8 beta 4.
Currently, the only way for iOS custom keyboards to interact with text is through <UITextDocumentProxy> and the only way to insert anything is via the insertText: method.
Here is the header for the insertText: method in <UITextDocumentProxy>:
- (void)insertText:(NSString *)text;
As you can see, it takes a plain NSString... not an NSAttributedString. This is why your attempt to insert an image doesn't work.
However, despite the fact that you can't add pictures, it is still very possible to insert emojis, since an emoticon is really just a Unicode character.
To add an emoji, just insert the proper Unicode character:
[self.textDocumentProxy insertText:#"\U0001F603"];
Useful links:
List of Unicode Emoji: http://apps.timwhitlock.info/emoji/tables/unicode
Unicode Characters as NSStrings: Writing a unicode character with NSString

iOS: Column formatting for NSString not working in UITextView?

I'm working on an iPad app and I need to be able to format some output on the screen in a columnar format. This was similar to my question:
How can I use the \t [tab] operator to format a NSString in columns?
and I used that solution, unfortunately I'm not seeing the same results. My code is as follows:
NSString* titleColumn = [[NSString stringWithFormat:#"%#", displayName] stringByPaddingToLength:25 withString:#" " startingAtIndex:0];
NSString* serializedValue = [[NSMutableString alloc] init];
NSString* valueAsString = [NSString stringWithFormat:#"%.03f", value];
serializedValue = [serializedValue stringByAppendingFormat:#"%#%#", titleColumn, valueAsString];
When logging the items in the console, they are properly aligned, however, when plugging them into a UITextView, they are misaligned. This is how I'm sticking them in the text view:
NSMutableString* displayString = [[NSMutableString alloc] initWithString:#""];
for (NSString* entry in textToDisplay)
{
NSLog(#"%#", entry);
[displayString appendString:entry];
[displayString appendString:#"\n"];
}
[self.fTextPanel setText:displayString];
Any ideas on what I'm doing wrong?
EDIT:
In the log, it looks like this:
Inclination 0.000
Version 0.000
Inferior/Superior 0.000
Anterior/Posterior 0.500
And the UITextView version looks like this: http://imgur.com/vrUzybP,OYxGVd8
The reason for misaligned is the different width for each character. The best way for displaying this type of information is by using UITableView, You can use title and subTitle field for displaying or you can design a custom UITableView.
the reason is because when drawing charachters (glymphs), each character will have different widths,i.e character small c and big C will take different widths for drawing , so it wont work. Even though there are two strings with equal lengths but different characters, the drawing text will have different widths.
What i would suggest you for this is to have two textViews side by side, render titles in one textVIew and values in the next TextView.
If the number of titles is large and if you enable scrolling in textVIews, use delegate Methods of UIScrollView, and when scrollHappens in either of them, set the contentOffset of the other to make it look like single TextView.
Hope this helps.

UISearchBar that Ignores Special Characters when Searching UITableView Cell

Thanks to the help of those on SO, I have a great UISearchBar that filters my UITableView. There is one more feature that I'd like to add.
I would like the UISearchBar filter to ignore special characters like apostrophes, commas, dashes, etc... and to allow cells with text like "Jim's Event" or "Jims-Event" to still come up if the user types "Jims Event".
for (NSDictionary *item in listItems)
{
if ([scope isEqualToString:#"All"] || [[item objectForKey:#"type"]
isEqualToString:scope] || scope == nil)
{
NSStringCompareOptions opts = (NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch);
NSRange resultRange = [[item objectForKey:#"name"] rangeOfString:searchText
options:opts];
if (resultRange.location != NSNotFound) {
[filteredListItems addObject:item];
}
}
}
Anyone have any ideas? Thank you!
This one is a little tricky. The first solution that comes to mind is to strip any character that you deliberately don't want to match from both the search and item strings, then do the comparison. You can use NSCharacterSet instances to do that filtering:
// Use this method to filter all instances of unwanted characters from `str`
- (NSString *)string:(NSString *)str filteringCharactersInSet:(NSCharacterSet *)set {
return [[str componentsSeparatedByCharactersInSet:set]
componentsJoinedByString:#""];
}
// Then, in your search function....
NSCharacterSet *unwantedCharacters = [[NSCharacterSet alphanumericCharacterSet]
invertedSet];
NSString *strippedItemName = [self string:[item objectForKey:#"name"]
filteringCharactersInSet:unwantedCharacters];
NSString *strippedSearch = [self string:searchText
filteringCharactersInSet:unwantedCharacters];
Once you have the stripped strings, you can do your search, using strippedItemName in place of [item objectForKey:#"name"] and strippedSearch in place of searchText.
In your example, this would:
Translate the search string "Jims Event" to "JimsEvent" (stripping the space)
Translate an item "Jim's Event" to "JimsEvent" (stripping the apostrophe and space)
Match the two, since they're the same string
You might consider stripping your search text of unwanted characters once, before you loop over item names, rather than redoing the same work every iteration of your loop. You can also filter more or fewer characters by using a set other than alphanumericCharacterSet - take a look at the class reference for more.
Edit: we need to use a custom function to get rid of all characters in the given set. Just using -[NSString stringByTrimmingCharactersInSet:] only filters from the ends of the string, not anywhere in the string. We get around that by splitting the original string on the unwanted characters (dropping them in the process), then rejoining the components with an empty string.

Objective-C crash on appending array to textview's text field

I'm newer to Objective-C though I have worked in Java, C, and C++ and I'm still learning Objective-C.
I have a socket, a receive data function, and a text view. As data comes in, I want to append it to the text view. Now my textview has some pre-populated text at the start. If in every call to receieve data that data comes in, I just get the current text of the text view, append it to itself in a nsstring with:
NSString *oldtext = [mTextViewAlias text];
NSString *toSend = [oldtext stringByAppendingString: oldtext];
and then set the text view to toSend, it works fine, and I see the data grow in my text view.
The problem is, I want to append:
UInt8 buffer[len]; // which has data from the socket. len is set to amount of data on each call of receive data as follows
int len = CFDataGetLength(df);
What I've been trying to do is convert a buffer to a nsstring and append. for example:
NSString *newdata = [NSString stringWithUTF8String: buffer];
it's occurred to me that buffer may not terminate with a '\0' character so I've even created a new buffer called char newbuffer[len+1]; and copied buffer into it and added a \0 as the last character.
I can append the first time around on the first pass of new data, but the second append, appending to something that had chars from buffer appended to the text once before always crashes.
I did a little trick where if len > 10 assign buffer[10]='\0'. And it actually let me grab data twice before crashing the third time.
It seems I have one of two problems and I'm not sure how to fix it. One is I can only grab as much data as is in the buffer and somehow these nsstrings are depending on it and when I change the buffer when receiving data, it is called again it causes the crash. Or maybe it's just still an issue with the '\0' not being there still though I don't see how.
Try something like this:
NSMutableData *buffer = [[NSMutableData alloc] init];
[buffer appendBytes:aCArray length:lengthOfaCArray];
NSString *newdata = [[NSString alloc] initWithData: buffer encoding:NSASCIIStringEncoding];
//When your finished with newdata and buffer, dont forget to release it
//This might be done automatically if you have Automatic Reference Counting (ARC) on
[newdata release];
[buffer release];
Full reference on the encoding types here.
No guarantees this works as I wrote this code from a Windows machine and a couple tabs open at Apple's developer site. But should help you in the right direction.

Resources