iOS 判断网址、链接地址、url地址是否可用

//思路:传入一个请求的URL,进行网络请求,如果返回失败信息则说明此URL不可用

//1.首先进行第一步判断传入的字符串是否符合HTTP路径的语法规则,即”HTTPS://” 或 “HTTP://” ,从封装的一个函数,传入即可判断

- (NSURL *)smartURLForString:(NSString *)str {

    NSURL *     result;

    NSString *  trimmedStr;

    NSRange     schemeMarkerRange;

    NSString *  scheme;

    assert(str != nil);

    result = nil;

    trimmedStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    if ( (trimmedStr != nil) && (trimmedStr.length != 0) ) {

        schemeMarkerRange = [trimmedStr rangeOfString:@"://"];

        if (schemeMarkerRange.location == NSNotFound) {

            result = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", trimmedStr]];

        } else {

            scheme = [trimmedStr substringWithRange:NSMakeRange(0, schemeMarkerRange.location)];

            assert(scheme != nil);

            if ( ([scheme compare:@"http"  options:NSCaseInsensitiveSearch] == NSOrderedSame)

                || ([scheme compare:@"https" options:NSCaseInsensitiveSearch] == NSOrderedSame) ) {

                result = [NSURL URLWithString:trimmedStr];

            } else {

                // 格式不符合

            }

        }

    }

    

    return result;

}


//判断

-(void) validateUrl: (NSURL *) candidate {

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:candidate];

    [request setHTTPMethod:@"HEAD"];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        NSLog(@"error %@",error);

        if (!request && error) {

            NSLog(@"不可用");

        }else{

            NSLog(@"可用%@",request);

        }

    }];

    [task resume];

}



 

你可能感兴趣的:(iOS 判断网址、链接地址、url地址是否可用)