赞
踩
最近做了一个项目,app内部打开连接,很多小伙伴都用得到,但是有运营小伙伴,直接输入www.XXX.com,前面没有加上http://或者https://,这样会导致请求不成功,后来查到了,话不多说上代码!
- - (NSString *)getCompleteWebsite:(NSString *)urlStr{
- NSString *returnUrlStr = nil;
- NSString *scheme = nil;
-
- assert(urlStr != nil);
-
- urlStr = [urlStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
- if ( (urlStr != nil) && (urlStr.length != 0) ) {
- NSRange urlRange = [urlStr rangeOfString:@"://"];
- if (urlRange.location == NSNotFound) {
- returnUrlStr = [NSString stringWithFormat:@"http://%@", urlStr];
- } else {
- scheme = [urlStr substringWithRange:NSMakeRange(0, urlRange.location)];
- assert(scheme != nil);
-
- if ( ([scheme compare:@"http" options:NSCaseInsensitiveSearch] == NSOrderedSame)
- || ([scheme compare:@"https" options:NSCaseInsensitiveSearch] == NSOrderedSame) ) {
- returnUrlStr = urlStr;
- } else {
- //不支持的URL方案
- }
- }
- }
- return returnUrlStr;
- }
- NSString *str = @"www.baidu.com";
- NSLog(@"%@",[self getCompleteWebsite:str]);
2016-04-08 15:40:26.818 ZFJAnimation[6100:155911] http://www.baidu.com
判断此路径是否能够请求成功,直接进行HTTP请求
- //判断此路径是否能够请求成功,直接进行HTTP请求
- - (void)urliSAvailable:(NSString *)urlStr{
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
- [request setHTTPMethod:@"HEAD"];
- NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
- NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
- if (error) {
- NSLog(@"不可用");
- }else{
- NSLog(@"可用");
- }
- }];
- [task resume];
- }
希望对你有所帮助!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。