ios - 通过使用由字符串分隔的组件从 url 获取值

标签 ios objective-c

我有一个看起来像这样的 url :

https://google.com/image/ghwUT23Y.jpeg

我希望能够实现这样的目标:

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/

相关文章:

ios - UITabBar 项目在选择时具有不同的颜色

ios - 如何防止 iOS 在 Swift 中自动为数字加下划线?

ios - 更改 iPhone 6 应用图标下的标题

Objective-C Box 2.0 文件上传 - 问题

ios - 如何将导航栏置于相机框架的顶部?

ios - 数组有追加,但里面没有值

objective-c - 滚动时表格单元格内容损坏

objective-c - 如何理解这个崩溃日志

iphone - iPhone 上 TableView 重用单元格的问题

ios - 来自谷歌驱动器的 objective-c 列表文件