通过使用由string分隔的组件从url获取值

时间:2017-11-24 09:23:11

标签: ios objective-c

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

  

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

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

section = image; 
value = ghwUT23Y; 

我试图爆炸网址并使用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作为一个部分?

2 个答案:

答案 0 :(得分:2)

您需要先将字符串转换为网址,然后使用pathComponents方法访问该网址的每个组件。

目标C:

git clone https://gitlab-ci-token:${Personal Access Tokens}@gitlab.com/username/myrepo.git

夫特

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

答案 1 :(得分:0)

斯威夫特:

func detectUrl()  {
    let strLongDescription = "https://google.com/image/ghwUT23Y.jpeg"

    if(strLongDescription.contains("image")){

        var arrString : [String] = strLongDescription.components(separatedBy: "google.com/")
        let lastOfarrString : String = arrString.last!
        arrString = lastOfarrString.components(separatedBy: "/")
        let section = arrString.first!
        let value = arrString.last! 
    }
}