当前位置:   article > 正文

iOS-判断输入的网址是http还是https,判断网址是否可用_ios判断域名是否可用

ios判断域名是否可用

前言

最近做了一个项目,app内部打开连接,很多小伙伴都用得到,但是有运营小伙伴,直接输入www.XXX.com,前面没有加上http://或者https://,这样会导致请求不成功,后来查到了,话不多说上代码!

拼接http://或者https://

  1. - (NSString *)getCompleteWebsite:(NSString *)urlStr{
  2. NSString *returnUrlStr = nil;
  3. NSString *scheme = nil;
  4. assert(urlStr != nil);
  5. urlStr = [urlStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  6. if ( (urlStr != nil) && (urlStr.length != 0) ) {
  7. NSRange urlRange = [urlStr rangeOfString:@"://"];
  8. if (urlRange.location == NSNotFound) {
  9. returnUrlStr = [NSString stringWithFormat:@"http://%@", urlStr];
  10. } else {
  11. scheme = [urlStr substringWithRange:NSMakeRange(0, urlRange.location)];
  12. assert(scheme != nil);
  13. if ( ([scheme compare:@"http" options:NSCaseInsensitiveSearch] == NSOrderedSame)
  14. || ([scheme compare:@"https" options:NSCaseInsensitiveSearch] == NSOrderedSame) ) {
  15. returnUrlStr = urlStr;
  16. } else {
  17. //不支持的URL方案
  18. }
  19. }
  20. }
  21. return returnUrlStr;
  22. }

示例如下:

  1. NSString *str = @"www.baidu.com";
  2. NSLog(@"%@",[self getCompleteWebsite:str]);

2016-04-08 15:40:26.818 ZFJAnimation[6100:155911] http://www.baidu.com

判断网址是否有效

判断此路径是否能够请求成功,直接进行HTTP请求

  1. //判断此路径是否能够请求成功,直接进行HTTP请求
  2. - (void)urliSAvailable:(NSString *)urlStr{
  3. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
  4. [request setHTTPMethod:@"HEAD"];
  5. NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  6. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  7. if (error) {
  8. NSLog(@"不可用");
  9. }else{
  10. NSLog(@"可用");
  11. }
  12. }];
  13. [task resume];
  14. }


希望对你有所帮助!微笑



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/731755
推荐阅读
相关标签
  

闽ICP备14008679号