user6107006 user6107006 - 3 months ago 14
Objective-C Question

replace in NSURL

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

Answer

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];