標籤:
思路:傳入一個請求的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 { // It looks like this is some unsupported URL scheme. } } } return result;}
第二步,判斷此路徑是否能夠請求成功,直接進行HTTP請求,觀察返回結果->
//判斷-(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 (error) { NSLog(@"不可用"); }else{ NSLog(@"可用"); } }]; [task resume];}
iOS-判斷URL是否可用,判斷網址是否正確