我有一个看起来像这样的 url :
我希望能够实现这样的目标:
section = image;
value = ghwUT23Y;
我尝试分解 url 并使用componentsSeperatedByString
方法来获取我需要的值。
if ([[explodedUrl firstObject] containsString:@"google.com"] && ![[explodedUrl firstObject] isEqualToString:@"https://google.com/"]) {
NSString *sectionString = [[[explodedUrl lastObject] componentsSeparatedByString:@"/"] firstObject];
NSLog(@"redirectttttt: %@",sectionString);
NSString *itemString = [[[explodedUrl lastObject] componentsSeparatedByString:@"/"] lastObject];
NSLog(@"redirectttttt:2 %@",itemString);
问题:
使用此方法,itemString
返回值:ghwUT23Y.jpeg
,但 sectionString
返回给我 https://
我怎样才能将 image
作为一个部分?
最佳答案
您需要先将字符串转换为 url 并使用 pathComponents访问该 url 的每个组件的方法。
Objective-C :
NSURL *url = [NSURL URLWithString:@"ttps://google.com/image/ghwUT23Y.jpeg"];
NSMutableArray *components = [[url pathComponents] mutableCopy];
NSString *fileName = [components lastObject];
[components removeLastObject];
NSString *section = [components lastObject];
NSLog(@"File : %@, Section: %@",fileName, section);
swift
let url = URL(string: "https://google.com/image/ghwUT23Y.jpeg")
var components = url?.pathComponents
let fileName = components?.popLast()
let section = components?.popLast()
关于ios - 通过使用由字符串分隔的组件从 url 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47470020/