Remove last "/" from string in Iphone SDK - iphone

I have a string like:
http://feedproxy.google.com/~r/MakePartsFast/~3/1dZEOLADapg/
I want to use this string to load html page. But because of "/" at last in string, I get the URL is as null.
my code is as follow:
NSURL *ur=[NSURL URLWithString:Mystring];
NSLog(#"%#",ur); //getting null value
NSURLRequest *requestObj = [NSURLRequest requestWithURL:ur];
NSLog(#"%#",requestObj);
So, How can i remove this last "/" from string??

Are you sure it's because of the last '/'? Could it be because of the '~' character in the middle?
Whichever way, to check for the last character, simply do
unichar last = [urlString characterAtIndex:urlString.length - 1];
if (last == '/')
urlString = [urlString substringToIndex:urlString.length - 1];

try this code ...
NSString *Mystring = #"http://feedproxy.google.com/~r/MakePartsFast/~3/1dZEOLADapg/";
if ([Mystring isEqualToString:#""]||[Mystring isEqual:nil]) {
NSLog(#"\n\n String is NULL");
}
else {
NSString *TempURl = [Mystring substringToIndex:[Mystring length]-1];
NSString *urlstr =[TempURl stringByReplacingOccurrencesOfString:#" " withString:#""];
urlstr =[urlstr stringByReplacingOccurrencesOfString:#"\n" withString:#""];
urlstr =[urlstr stringByReplacingOccurrencesOfString:#"\t" withString:#""];
[urlstr retain];
NSURL *ur=[NSURL URLWithString:urlstr];
NSLog(#"%#",ur); //now get string value here
// NSURLRequest *requestObj = [NSURLRequest requestWithURL:ur];
//
// NSLog(#"%#",requestObj);
}
I Got Log OutPut : http://feedproxy.google.com/~r/MakePartsFast/~3/1dZEOLADapg
hope this help you...

If you are sure that you need to remove the last character from string in every case, then you can get a newString as
NSString *newString = [oldString substringToIndex:[oldString length]-1];

I think you need to encode the string like:
NSString *encodedString = [Mystring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

try this may help you
NSString * Mystring=#"http://feedproxy.google.com/~r/MakePartsFast/~3/1dZEOLADapg/";
[alfa substringToIndex:alfa.length-1];

Related

url Encoding in ios

I get a link from server to image has already been Encoding so it comes with %20
But sometimes I get a code include Hebrew characters, so I need to do Encoding agian , With the above code:
But after my Encoding i get in response that % 20 change to % 2520
static CFStringRef charsToEscape = CFSTR("&=");
+ (NSString *)escapeStringByAddingPercentEscapes: (NSString*) string {
return [(NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)string,
NULL,
charsToEscape,
CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) autorelease];
}
i tried to add % to charsToEscape like this:
static CFStringRef charsToEscape = CFSTR("&=%");
but it did not help.
thanks
NSString *urlString = #"----YOUR URL HERE----";
[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
Your idea is good if I did not get the Hebrew characters in the link.
But I found the solution , I just sent the % in the parameter legalURLCharactersToBeEscaped
now i use in the function like this:
static CFStringRef charsToEscape = CFSTR("&=");
static CFStringRef charsUnchanged = CFSTR("%");
+ (NSString *)escapeStringByAddingPercentEscapes: (NSString*) string {
return [(NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)string,
charsUnchanged,
charsToEscape,
CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) autorelease];
}
thanks

how to remove ( from string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
iphone sdk - Remove all characters except for numbers 0-9 from a string
i have string with a phone number as
mynumber = #"(334)687-6619";
I am using
NSString *phoneURLString = [NSString stringWithFormat:#"tel:%#", phoneNumber];
NSURL *phoneURL = [NSURL URLWithString:phoneURLString];
[[UIApplication sharedApplication] openURL:phoneURL];
to make a call.
But due to "(" , ")" my method is not able to make a call.
Please suggest me to make a right string
something like
"1-800-555-1212" or something like that.
Thanks
You can Use
NSString *s = #"(334)687-6619";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"("];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #""];
s = [s stringByReplacingOccurrencesOfString:#")" withString:#"-"];
NSLog(#"%#", s);
So, It will replace "(" with "" & replace ")" with "-".
Thanks.
use this code
NSString *str = #"(334)687-6619";
str = [str stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:#""];
str = [str stringByReplacingCharactersInRange:NSMakeRange(3, 1) withString:#"-"];
NSLog(#"%#",str);
OUTPUT is: 334-687-6619
To remove characters from a string:
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"()"];
NSArray *comps = [string componentsSeparatedByCharactersInSet:set];
NSString *newString = [comps componentsJoinedByString:#""];

Character replacing in Xcode - Objective-C

I have used this code for replacing "\n" with "", but it is not working.
How can I do it?
NSString *descString = [values objectForKey:#"description"];
descString = [descString stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSLog(#"Description String ---->>> %#",descString);
catlog.description = descString;
[webview loadHTMLString:catlog.description baseURL:nil];
webview.opaque = NO;
try this
NSString *s = #"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #""];
NSLog(#"%#", s);
descString = [descString stringByReplacingOccurrencesOfString:#"\\n" withString:#""];
For more information refer to stringByReplacingOccurrencesOfString:withString: method
Hope this helps you.
UPDATE
Swift 3.0
descString.replacingOccurrences(of: "\\n", with: "");
and If I am not wring it will also work for Swift 4.0

xcode - decode xml output string

NSString *col1 = [aBook.name stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#" \n\t"]];
NSLog(#"column1: %#", col1); //output:- ABC+Company
This is my xml data output.
It comes with '+' mark. How can i decode this?
Could you please help me?
You mean get the parts that are seperated by the '+' sign? You can do that with:
NSArray *stringArray = [col1 componentsSeparatedByString:#"+"];
[stringArray objectAtIndex:0]; //ABC
[stringArray objectAtIndex:1]; //Company
If you want to remove/replace the '+' sign you can do this:
NSString* string = [col1 stringByReplacingOccurrencesOfString:#"+" withString:#""]; //last string can be empty or have a string value
Hope this helped you!
You can also replace the plus signs with spaces, if that’s what you’re after:
NSString *name = [col1 stringByReplacingOccurrencesOfString:#"+" withString:#" "];

Make an NSURL with an encoded plus (%2B)

I need to pass a timestamp with a timezone offset in a GET request, e.g.,
2009-05-04T11:22:00+01:00
This looks like a two arguments "2009-05-04T11:22:00" and "01:00" to the receiving PHP script (over which I've no control).
NSURL doesn't encode plus signs, but if I make an NSURL using the string
2009-05-04T11:22:00%2B01:00
the url I end up with contains:
2009-05-04T11:22:00%252B01:00
Any ideas how I can preserve my encoded plus sign or just plain prevent NSURL from encoding anything?
What worked for me was doing the UTF8 conversion, then replacing the + sign with %2B:
NSString *urlString =
[NSString stringWithFormat:#"%#/iphone/push/create?pn[token]=%#&pn[send_at]=%#",
kHTTPURL, appDelegate.deviceAPNToken, [dateTimeToUse description]];
urlString =
[[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
The string should be URL encoded.
Here is a category for NSString that will help:
NSString+Additions.h
#interface NSString (Additions)
- (NSString *)stringByURLEncoding;
NSString+Additions.m
#import "NSString+Additions.h"
#implementation NSString (Additions)
- (NSString *)stringByURLEncoding {
return (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
}
Use NSString's stringByAddingPercentEscapesUsingEncoding: method on the text you want to include as an argument.
As its name implies, the method will convert return an auto-released string containing an url-safe version of the receiver.
Thought I may as well provide my workaround as an answer, as I don't think there's a good solution to the original problem.
The plus sign (+) is completely valid in a URL, so my solution was to convert the time to GMT and remove the timezone/DST offset from the string. I'll leave it as an exercise for the reader to determine the value of secondsFromGMT below as, in my case, it's always the same because I'm only interested in timestamps generated by a web server.
NSString *gmtWhen = [[self descriptionWithCalendarFormat:nil
timeZone:[NSTimeZone
timeZoneForSecondsFromGMT:secondsFromGMT
] locale:nil] stringByReplacingOccurrencesOfString:#" +0000" withString:#""];
Solution when using URLComponents (Swift 3):
var params = ["email": "user+ios-default#example.com", "name": "John Brown"]
var components = URLComponents(string: "http://www.example.com")!
components.path = "/login"
components.queryItems = params.map { URLQueryItem(name: $0, value: $1) }
let url_NoFix = components.url!
// http://www.example.com/login?name=John%20Brown&email=user+ios-default#example.com
let cs = CharacterSet(charactersIn: "+").inverted
let q = components.percentEncodedQuery?.addingPercentEncoding(withAllowedCharacters: cs)
components.percentEncodedQuery = q
let url_Fixed = components.url!
// http://www.example.com/login?name=John%20Brown&email=user%2Bios-default#example.com
encode you string by using below code
NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,NULL,(CFStringRef)#"+",kCFStringEncodingUTF8);
this will encode + of you string which will prevent replacement of + by %2b while posting data in post method
To get encoded plus (%2B) (It works with all charcters) use CFURLCreateStringByAddingPercentEscapes as
/**
get parameterized url from url and query parameters.
*/
+(NSString *)getParameterizedUrl:(NSString *)url withParameters:(NSDictionary *)queryDictionary
{
NSMutableArray *mutablePairs = [NSMutableArray array];
for (NSString *key in queryDictionary) {
[mutablePairs addObject:[NSString stringWithFormat:#"%#=%#", CTPercentEscapedQueryStringKeyFromStringWithEncoding(key, NSUTF8StringEncoding), CTPercentEscapedQueryStringValueFromStringWithEncoding(queryDictionary[key], NSUTF8StringEncoding)]];
}
return [[NSString alloc]initWithFormat:#"%#?%#",url,[mutablePairs componentsJoinedByString:#"&"]];
}
static NSString * const kCharactersToBeEscapedInQueryString = #":/?&=;+!##$()',*";
static NSString * CTPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
static NSString * const kCharactersToLeaveUnescapedInQueryStringPairKey = #"[].";
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
}
static NSString * CTPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
}
And use in your code as
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setObject:#"2009-05-04T11:22:00+01:00" forKey:#"timestamp"];
NSString *urlString = [self getParameterizedUrl:#"http://www.example.com" withParameters:params];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];