How can I do a string replace in NSURL
?
I tried stringByReplacingOccurrencesOfString
but it works with NSString
.
NSURL *imageURL = [NSURL URLWithString:dataList[indexPath.item][@"image"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
I want to replace image url
http://example.com/image1.jpg
to
http://example.com/img1.jpg
NSURL
has an absoluteString
method that you could use like so
NSURL *imageURL = [NSURL URLWithString:dataList[indexPath.item][@"image"]];
NSString *urlString = [imageURL.absoluteString stringByReplacingOccurrencesOfString:@"image" withString:@"img"];
imageURL = [NSURL URLWithString:urlString];
You could also directly operate on the NSString from the dataList as well:
NSString *urlString = [dataList[indexPath.item][@"image"] stringByReplacingOccurrencesOfString:@"image" withString:@"img"];
imageURL = [NSURL URLWithString:urlString];
NSURL *imageURL = [NSURL URLWithString:dataList[indexPath.item][@"image"]];
NSString *urlString = [imageURL.absoluteString stringByReplacingOccurrencesOfString:@"image" withString:@"img"];
NSString *webStringURL = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
imageURL = [NSURL URLWithString:webStringURL];
Hope This will help you.
You are going to replace the last path component of the URL so use the dedicated API of NSURL
:
NSURL *imageURL = [NSURL URLWithString:dataList[indexPath.item][@"image"]];
NSURL *newURL = [[imageURL URLByDeletingLastPathComponent] URLByAppendingPathComponent:@"img.jpg"];
NSData *imageData = [NSData dataWithContentsOfURL: newURL];
stringByReplacingOccurrencesOfString
could cause unexpected behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With