如何检查NSString包含URL或字符串数​​据?

时间:2013-10-11 12:27:28

标签: objective-c cocoa

我对iOS更新,我在检查字符串对象包含URL或字符串时遇到问题?

NSMutableArray *Arr=[NSMutableArray alloc]initWithObject:@"Welcome", @"http://abcd.com/Images/bus.png", nil];

int i;

i++;

NSString *str=[Arr objectAtIndex:i];

现在,我想检查条件,如果字符串包含“欢迎”,必须在标签上显示或者如果是URL,我需要在ImageView中显示该URL图像。那我怎么检查呢?请帮我解决这个问题。

4 个答案:

答案 0 :(得分:1)

不要将两者都作为NSStrings启动,而是尝试通过将URL设置为NSURL(专用于URL的特殊容器)来区分它们:

NSMutableArray* Arr = [NSMutableArray alloc]initWithObject:@"Welcome", [NSURL URLWithString:@"http://abcd.com/Images/bus.png"], nil];

for(id object in Arr)
{
    if([object isKindOfClass:[NSString class]])
    {
        NSString* string = object;
        NSLog(@"String: %@", string);
    }
    else if([object isKindOfClass:[NSURL class]])
    {
        NSURL* url = object;
        NSLog(@"URL: %@", url);
    }
}

答案 1 :(得分:1)

试试这个

NSMutableArray *Arr=[[NSMutableArray alloc]initWithObjects:@"Welcome", @"http://abcd.com/Images/bus.png",nil];

    NSString *st=nil;
    for(NSString *string in Arr)
    {
     NSArray *matches = [detector 
                 matchesInString:string
                                    options:0
                                      range:NSMakeRange(0,     
                                     [string length])];
   for (NSTextCheckingResult *match in 
          matches) {
          if ([match resultType] ==    
         NSTextCheckingTypeLink) {
        NSURL *url = [match URL];
         } else 
       {
        NSlog(@"it is a string");
       }
    }

}

答案 2 :(得分:0)

要检查NSString是否包含网址您可以尝试使用此代码

if ([stringName hasPrefix:@"http://"] || [stringName hasPrefix:@"https://"]) {
    //show imageVivew
} 

答案 3 :(得分:0)

试试这个,它会对你有所帮助:

NSMutableArray *Arr=[[NSMutableArray alloc]initWithObjects:@"Welcome", @"http://abcd.com/Images/bus.png", nil];

if([Arr count])

{

for (NSString *str in Arr)

    {
        if([str isEqualToString:@"Welcome"])

        {
            NSLog(@"str is %@",str);

            //do whatever you want
        }

        if([str isEqualToString:@"http://abcd.com/Images/bus.png"])

        {
            NSLog(@"str is %@",str);

            //do whatever you want
        }
    }
}