split string in ios string from json data? - ios

I have one string. Now I wanted to split this string. For static separation I know the code but I don’t code for dynamic value.
my string is
NSString *str = #"https://graph.facebook.com/v2.5/181054825200000/feed?fields=created_time,message,picture,full_picture,comments.limit%280%29.summary%28true%29,likes.limit%280%29.summary%28true%29&limit=5&format=json&access_token=CAALjFrE5mNYBAOg1EDiUrsE2kr1kIRrLIv7g4OweSMvHso2exB5Dttshn7dgOlW24ZCXSnDZAWiV6xMUKXedTXUhiHpdmZBPCGzD1orFlrLRP2gaBZCbZBZBnjUHewF9hZBmJKxtiwVzpw9gnnQXk5Hfx0ZBM2ksAUzkSWR5feaNMbf3UUmUpJlxeh0gKdDrzWBvIJRPy0xGqL0ZAMFsRhyCZCTX42l1sZAceZB0VCeDZB95mrAZDZD&until=1456345291&__paging_token=enc_AdCKD3tSYMoZB3MCKaJkYnbVmBgUyY2tBceGDD2G1hqxRDiQKZCsSbmvWZASLvlCMf0BVzq2uZAScSWp7ZAavZB2d72BIHJISefk09noRuv9gA5b5hFwZDZD";
but i don’t how to show any value dynamically .(for e.g. until (in string))
please help me for this issue.
Thank You.

If you are parsing a URL you should really use NSURLComponents. It makes breaking a URL into the different parts much easier, and the code is tested and verified by Apple.

For separate string by a separator you can use this.
NSString *url = #"<url>";
NSArray *array = [url componentsSeparatedByString:#"<seperator string>"];
NSLog(#"%#", array);
But for URL parsing ,As per Duncan's answer, yes it is good to parse a URL using NSURLComponents. By using this class you can get any desired part of an URL.

Related

Remove Space After a Particular Character

I have an string which is coming from a server :
<p>(555) 555-5555 </p>
I want to remove any space after teland up to 10 characters.
For removing only spaces between characters you can use this
NSString *strNum = #"(555) 555-5555";
strNum = [strNum stringByReplacingOccurrencesOfString:#" " withString:#""];
Hope this will help you..!! :)
Removing spaces is called Trimming. You can find a possible solution here, or here
Solution copied here in case links break :
NSString *string = #" this text has spaces before and after ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
This is slightly better than replacing " " with "", because it uses the charset, and you "never know how white spaces are gonna be in other character sets". The OS does know, so better trust it.
Since your question isn't 100% clear, I'm assuming that is what you need, but feel free to comment for more help :)
EDIT : I might have misunderstood you. If you need to remove all spaces in the string, you could just use Abha's answer.
EDIT 2 : Okay we're about to solve this outstanding mystery.
You want to trim ALL spaces after telinside your string.
What you need to do (and for the sake of learning I'm not gonna write code) is :
Find (using available NSString methods) the word telinside the string. Once you found it, you can find it's index inside the string (after all, a string is just an array of char).
Once you have the index, you just have to use Abha's answer (replace occurences of " " with "") in the range starting with the index you found and ending at that index + 10 (or whatever number you need).
It should be between 2 to 5 lines long, using various NSString methods or, if you really want to, a loop.
Answers you should check for inspiration :
Find string in string
Replace characters in range
Find index of char in string
Though, for the sake of conversation, I'm assuming you only need the phone number (not the tel). So removing ALL spaces should be enough (again, Abha's answer). I don't see any reason why you would take particular care for the first portion of the string when you probably won't use it anyway. Maybe I'm wrong but, you're saying you're new and I'm thinking you're approaching this the wrong way.
Also, to add something else, if you have any control over the server, the server itself should not send tel:(555) 555 5555. That's prone to mistakes. Either the server sends a string to be displayed, with proper characters and nice writing, like Telephone : (555) 555 5555", or you receive ONLY the phone number in a phone object (json or something), like 5555555555. If you have any control over the server, make it send the correct information instead of sending something not practical and having to rework it again.
Note that usually, it's the second option. The server sends something raw, and you just modify it to look good if necessary. Not the other way around.
You need to use NSMutableString class and its manipulation functions provided itself.
NSMutableString *muString = [NSMutableString stringWithString:#"(555) 555-5555"];
[muString insertString:#"" atIndex:10];
Some methods to split your string :
substringFromIndex:
substringWithRange:
substringToIndex:
Edit:
If your string is dynamic and you really dont know the index from where you need to remove extra spaces use below method of NSString class:
stringByReplacingOccurrencesOfString: Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
Example:
NSString *yourStr = #"(555) 555-5555"; // needs to remove spaces and all
yourStr = [yourStr stringByReplacingOccurrencesOfString:#" " withString:#""]; // after manipulation
Or if you really need to do some more advance changes into your string use NSMutableString class see detail below and example above on the top:
NSMutableString: The NSMutableString class declares the programmatic interface to an object that manages a mutable string—that is, a string whose contents can be edited—that conceptually represents an array of Unicode characters. To construct and manage an immutable string—or a string that cannot be changed after it has been created—use an object of the NSString class.
So you want to remove space from first 10 character, which you think is a tel number, right?
So make a sub string and replace space from that.
NSString *str = #"(555) 555-5555";
NSString *firstPart = [[str substringToIndex:10] stringByReplacingOccurrencesOfString:#" " withString:#""];
then take the second part and merge it.
NSString *secondPart = [str substringFromIndex:10];
NSMutableString *finalString = [NSMutableString stringWithFormat:#"%#%#",firstPart,secondPart];
Is this what you want to do? I've written in step by step for better understanding.
This solution in not generic but may work on your condition
NSString * serverString;
NSArray* stringComp = [serverString componentsSeparatedByString:#"\\"];
NSString* stringOfTel = [stringComp objectAtIndex:1];
NSString* withOutSpaceTel = [stringOfTel stringByReplacingOccurrencesOfString:#" " withString:#""];
serverString = [serverString stringByReplacingOccurrencesOfString:stringOfTel withString:withOutSpaceTel];
and your will get your serverstring with space you want.
Again this may work only for your current solution.
NSString *string = #"(555) 555-5555" //here you need to assign string which you are getting from server
NSString *resultString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
resultString will be the string with no space at start and end of the string.
Hope this helps!

ios issue with stringByAddingPercentEscapesUsingEncoding

In my app I need to send some parameters to the url, when I am trying with the stringByAddingPercentEscapesUsingEncoding it is not converting correctly. If I am not using this encoding I am getting null(Exception) from the nsurl.Here is me code.
http://www.mycompurl.co?message=xyz&id=____ here I am sending the id 1 or 2 or any number.
when I convert this string to url by using stringByAddingPercentEscapesUsingEncoding I got
"http://www.mycompurl.co?message=xyz&id=**%E2%80%8B**1" (when I send 1 as parameter). Then I got the 0 data from the Url.
str = [NSString stringWithFormat:#"%#?message=xyz&id=​%#",Application_URL,bootupdateNew];
str = [str stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
url=[NSURL URLWithString:str];
NSError* error = nil;
data1 = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
Thank you In advance
Basics
A URL is composed of several components.
Each component has its own rule how the component's source string must be encoded, so that this component becomes valid within the URL string.
Applying stringByAddingPercentEscapesUsingEncoding: will never always produce a correct URL if the string consists of more than one component (and if we assume, we have an unbounded set of source strings - so that the encoded string actually differs from the source string).
It even won't work always with a string which represents any single component.
In other words, for what's worth, stringByAddingPercentEscapesUsingEncoding: should not be used to try to make a URL out of several components. Even getting the URL query component correctly encoded is at least error prone, and when utilizing stringByAddingPercentEscapesUsingEncoding: it still remains wonky. (You may find correct implementations on SO, though - and I posted one myself).
But now, just forget about it:
It took awhile for Apple to recognize this failure, and invented NSURLComponents. It's available since iOS 7. Take a look! ;)

Serialize JSON string SBJSON vs NSJSONSerialization vs anything else?

I am receiving this JSON string and want to know how to serialize it into a dictionary so that I can parse it into a managed object.
I have looked at a few ways (named in the title), and can't seem to find the simplest, quickest alternative. I would like to use NSJSONSerialization, but I'm not sure it is made to do this?
Code where string comes in
NSString *data = [[NSString alloc]initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"String %#",data);
NSLog message
String [{"0":"1","id":"1","1":"re ee","name":"re ee","2":"http:\/\/ree.com\/images\/re.png","backgroundImageUrl":"http:\/\/ree.com\/images\/re.png","3":"http:\/\/ree.com\/images\/re.png","logoImageUrl":"http:\/\/ree.com\/images\/re.png"}]<br />
Thank you in advance
JSONKit is what your are looking for.
Besides the ease of use, it's quicker than SBJSon, even quicker than NSJSONSerialization.
For your example, your can get an array like this:
NSArray* arrayFromJson = [data objectFromJSONString];
NSString* id = arrayFromJson[0][#"id"];
Easy, huh?

Cut one string into two others in Objective-C

I have an NSURLRequest being made that to a server that returns a string.
string = [[NSMutableString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
receivedData is the mutable array that the downloaded data is stored in. Everything works fine.
I have now, however, added another value to that string. An example of the returned string would be 14587728000000 , 376.99. Originally it was one value so I didn't have to do any splicing. But, now that I have another value, I want to be able to separate it into two different strings.
What should I do to separate the two values into different string? Some kind of search that goes till the first space, or something like that. I have access to the server, and the string is generated in PHP so the separator can be anything.
You can do this with the NSString componentsSeparatedByString method:
NSString *string = #"14587728000000,376.99";
NSArray *chunks = [string componentsSeparatedByString: #","];
You can find some other common NSString tricks (where I found this one) here.
Use -(NSArray *)componentsSeparatedByString: and pass in the token to split by.

Converting between NSData and base64 strings

What is the easiest and fastest code to do a conversion between NSData and a base64 string? I've read a bunch of solutions at SO and mostly they involve in adding another class etc. I found a great solution here but it's too complex.
Scroll down to the Conclusion section on the page you linked and download the provided NSData+Base64 files. Its the best solution I have seen so far and is incredibly easy to use. If you can learn anything about Cocoa, you can learn to use that project.
Example
NSString *originalString = [NSString stringWithFormat:#"test"];
NSData *data = [NSData dataFromBase64String:originalString];
NSLog([data base64EncodedString]);
The above will print out the original string after converting it to base64 and back to a normal unencoded string.
As of iOS 7, NSData now directly provides this functionality with the new methods -base64EncodedDataWithOptions: and -base64EncodedStringWithOptions:. (The options let you specify that the string is/should be line-wrapped, the better to deal with email, and user-facing displays.)
You don't need any custom implementation. Creating base64 from NSData is shown in other answers. There is opposite direction. From Base64 string to NSData:
NSString *base64Encoded = #"some base64 string";
NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:base64Encoded options:0];
I ended up using this same class as provided by SUDZC
implementation was easy first I did an import
#import "NSData+Base64.h"
then I was able to call my data.
NSData *data = [[NSData alloc] initWithData:[NSData dataWithBase64EncodedString:strData]];
Be aware that there are more Base64 formats.
For example JWTs use a URL safe format.
Or you may take a look to the (quite new) CryptoCompatibility sample project, I think there is a wrapper class for base64 operation. It is a MacOS sample but it uses the library libresolve.dylib with I think is available on iOS too (is see it at least here in iOS7).

Resources