2016-09-07 51 views
5

如何在NSURL中更換字符串? 我試過stringByReplacingOccurrencesOfString,但它適用於NSString在NSURL中替換

NSURL *imageURL = [NSURL URLWithString:dataList[indexPath.item][@"image"]]; 
NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; 
UIImage *image = [UIImage imageWithData:imageData]; 

我要替換圖像的URL

http://example.com/image1.jpg 

http://example.com/img1.jpg 

回答

3

NSURL有一個absoluteString方法,你可以使用像這樣

NSURL *imageURL = [NSURL URLWithString:dataList[indexPath.item][@"image"]]; 

NSString *urlString = [imageURL.absoluteString stringByReplacingOccurrencesOfString:@"image" withString:@"img"]; 

imageURL = [NSURL URLWithString:urlString]; 

你可以人所以直接上的NSString從DataList的操作,以及:

NSString *urlString = [dataList[indexPath.item][@"image"] stringByReplacingOccurrencesOfString:@"image" withString:@"img"]; 

imageURL = [NSURL URLWithString:urlString]; 
+0

謝謝。這是工作 – OsamahM

+0

不客氣。請接受答案,如果它幫助你:) – akdsouza

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

希望這會幫助你。

1

您要更換URL的最後一個路徑組件,以便使用NSURL專用API:

NSURL *imageURL = [NSURL URLWithString:dataList[indexPath.item][@"image"]]; 
NSURL *newURL = [[imageURL URLByDeletingLastPathComponent] URLByAppendingPathComponent:@"img.jpg"]; 
NSData *imageData = [NSData dataWithContentsOfURL: newURL]; 

stringByReplacingOccurrencesOfString可能會導致意外的行爲。