Idea: Pass in a request URL, make a network request, if return failure information indicates this URL is not available
1. First, the first step is to determine whether the incoming string conforms to the syntax rules of the HTTP path, that is, "https://" or "http://", from the encapsulated function, passed in can be judged
- (Nsurl*) Smarturlforstring: (NSString*) str{Nsurl* result;NSString* TRIMMEDSTR;NsrangeSchememarkerrange;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 = [Nsurlurlwithstring:[NSStringstringwithformat:@"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 = [NsurlURLWITHSTRING:TRIMMEDSTR]; }Else{//It looks like this is some unsupported URL scheme.} } }returnResult;}
The second step is to determine if the path can be successfully requested, make an HTTP request directly, observe the return result
//Judgment-(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(@"Not Available"); }Else{NSLog(@"Available"); } }]; [Task resume];}
ios-to determine if URLs are available, and to determine if URLs are correct