Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 721
OsamahM Avatar asked Sep 07 '16 04:09

OsamahM


3 Answers

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];
like image 73
batman Avatar answered Oct 12 '22 01:10

batman


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.

like image 33
Amir Khan Avatar answered Oct 12 '22 01:10

Amir Khan


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.

like image 28
vadian Avatar answered Oct 12 '22 02:10

vadian