I'm a junior developer, and I got a code for this:
(NSString *)encodedStringFromObject:(id)object {
return [[object description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
But in 9.0 have to use stringByAddingPercentEncodingWithAllowedCharacters.
How Could I transfer this code ?
I need help, Thanks!
If you want just fast example look at this code:
NSString * encodedString = [#"string to encode" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
Also check List of predefined characters sets
If you want explanation read the documents or at least this topic: How to encode a URL in Swift
URL = [[NSString stringWithFormat:#"%#XYZ",API_PATH]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
You'd read the spec for both functions. Then you would find out for what purpose characters are replaced with escape sequences. From there you would find out the set of allowed characters, which must be documented somewhere.
That's an essential part of changing from junior to normal to senior developer: Find out exactly what your code is supposed to do, which should be defined somewhere, and then make it do what it should do.
stringByAddingPercentEscapesUsingEncoding is probably deprecated because it doesn't know which characters are allowed and sometimes gives the wrong results.
You can use stringByRemovingPercentEncoding instead of stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding
[#"string" stringByRemovingPercentEncoding];
Here is solution to do in Swift
var encodedString = "Hello, playground".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)
Related
The question title says it all, really. In swift you use "\()" for string interpolation of a variable. How does one do it with Objective-C?
There is no direct equivalent. The closest you will get is using a string format.
NSString *text = #"Tomiris";
NSString *someString = [NSString stringWithFormat:#"My name is %#", text];
Swift supports this as well:
let text = "Tomiris"
let someString = String(format: "My name is %#", text)
Of course when you use a format string like this (in either language), the biggest issue is that you need to use the correct format specifier for each type of variable. Use %# for object pointers. Use %d for integer types, etc. It's all documented.
#rmaddy's Answer is the gist of it. I just wanted to follow up on his comment that "It's all documented". Well, these symbols like %# and %d are called String Format Specifiers the documentation can be found at the following links.
Formatting String Objects
https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/FormatStrings.html
String Format Specifiers
https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1
Just telling us noobs "It's all documented" isn't very helpful because often (if you're like me) you googled to find this stackoverflow post at the top of the SEO. And taking the link in hopes of finding the original documentation!
http://mobile.gunsel.ua/index.php?r=Rupages&jsonRequest={"id_page":"2"}
So,how can I create a NSURL(and after request) from this URL.(I use NSJSONSerilization).
I'm new to iOS development please help me. Thank You!
Don't offer links on apple documentation.
Not sure I get what you are asking, but you can use a string, then format it with your JSON (I.e concatenate the params), then create an NSUrl from that string.
stringWithFormat
Should do the trick.
I'm not sure if that answered your question, but you need to elaborate if that's not the case.
i'm found out!! This is was associated with Encoding)))
NSString sampleUrl = #"mobile.gunsel.ua/index.php?r=Rupages&jsonRequest={\"id_page\":\"2\"}";
NSString encodedUrl = [sampleUrl stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];
So I have done some searching around so that I could see what it was I was doing with my code, and I couldn't find any answers as to what this very one specific line of code does.
NSString* name = [NSString stringWithUTF8String:countryName];
I know what the rest does (I only had to google how to do this part), it is supposed to take my char* (countryName) and turn it into an NSString so later on I can compare it with the
isEqualToString:
thing. I would just like to know what the following is actually doing to the char, and what does the UTF8String even mean?
I have barely any Objective C programming experience so any feedback is helpful :D
you are not totally right.
this method
Returns a string created by copying the data from a given C array of UTF8-encoded bytes.
so, UTF-8 string here is just a C array of bytes.
Check the documentation here.
It doesn't do anything to the char * string. It's just the input to the method. stringWithUTF8String takes a C-style string (in UTF-8 encoding), and creates an NSString using it as a template.
I have a Mac application that keeps it's own log file. It appends info to the file using NSString's writeToFile method. One of the things that it logs are URL's of web services that it is interacting with. To encode the URL, I'm doing this:
searchString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)searchString, NULL, (CFStringRef)#"!*'();:#&=+$,/?%#[]", kCFStringEncodingUTF8 );
The app then appends searchString to the rest of the URL and writes it to the log file. Now the problem is that after adding that URL encoding line, nothing seems to be getting written to the file. The program functions as expected otherwise however. Removing the line of code above results in all of the correct information being logged to the file (removing that line is not an option because searchString must be URL encoded).
Oh and I am using NSUTF8StringEncoding when writing the NSString to the file.
Thanks for any help.
EDIT: I know there's also a similar function to CFURLCreateStringByAddingPercentEscapes in NSString, but I've read that it doesn't always work. Can anyone shed some light on this if my original question cannot be answered? Thanks! (EDIT: same problem occurs when using stringByAddingPercentEscapesUsingEncoding:)
EDIT 2: Here's the code that I'm using to append messages to the log file.
+(void)logText:(NSString *)theString{
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:#"Folder/File.log"];
NSString *fileContents = [[[NSString alloc] initWithContentsOfFile:path] autorelease];
if([fileContents lengthOfBytesUsingEncoding:NSUTF8StringEncoding] >= 204800){
fileContents = #"";
}
NSString *timeStamp = [[NSDate date] description];
timeStamp = [timeStamp stringByAppendingString:#": "];
timeStamp = [timeStamp stringByAppendingString:theString];
fileContents = [fileContents stringByAppendingString:timeStamp];
fileContents = [fileContents stringByAppendingString:#"\n"];
[fileContents writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
}
Because after almost a whole day no one else has offered any answers, I'm going to post a wild guess here: you're not accidentally using the string you want to output (with percent characters in it) as a format string are you?
That is, making the mistake of doing:
NSLog(#"In format strings you can use %# as a placeholder for an object, and %i for a plain C integer.")
Instead of:
NSLog(#"%#", #"In format strings you can use %# as a placeholder for an object, and %i for a plain C integer.");
But I'm going to be surprised if this turns out to be the cause of your problem, as it usually causes random-looking output, rather than absolutely no output. And in some cases, Xcode also gives compiler warnings about it (when I tried NSLog(myString), I got "warning: format not a string literal and no format arguments").
So don't shoot me down if this answer doesn't help. It would be easier to answer your question if you could show us more of your logging code. As for the one line you provided, I can't detect anything wrong with it.
Edit: Oops, I kind of missed that you mentioned you're using writeToFile:atomically:encoding:error: to write the string to the file, so it's even more unlikely you're accidentally treating it as a format string somewhere. But I'm going to leave this answer up for now. Again, you should really show us more of your code though ...
Edit: Regarding your question on a method in NSString that has similar percent encoding functionality, that would be stringByAddingPercentEscapesUsingEncoding:. I'm not sure what kind of problems you're thinking of when you say you've heard it doesn't always work. But one thing is that CFURLCreateStringByAddingPercentEscapes allows you to specify extra characters that don't normally have to be escaped but which you still want to be escaped, while the method of NSString doesn't allow you to specify this.
Here are two ways to make a NSString.
NSString *sBody = [NSString stringWithString:#"Hello"]
versus
NSString *sBody = #"Hello"
Most of the time, I see it the first way. But is it also "clean" to use the second, or is it better to not use it?
Thanks and have a nice day!
They are equivalent. It's less code to use the literal (the second example), so I would just use that.
It's the same, the first way you're helping the compiler but it already does a great job optimizing string vars.