如何检查rtmp或hlsurl是否存在或他们会给迅速404错误

我需要从rssparsing一些数据,并从swift 2中打开相关的链接从parsingrss,例如我想检查这个链接是否有效:

rtmp://185.23.131.187:1935/live/jomhori1 

或者这个:

 http://185.23.131.25/hls-live/livepkgr/_defint_/liveevent/livestream.m3u8 

我的代码来检查url的validation:

 let urlPath: String = "http://185.23.131.25/hls-live/livepkgr/_defint_/liveevent/livestream.m3u8" let url: NSURL = NSURL(string: urlPath)! let request: NSURLRequest = NSURLRequest(URL: url) let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil var valid : Bool! do { _ = try NSURLConnection.sendSynchronousRequest(request, returningResponse: response) } catch { print("404") valid = false } 

我search了网页,但是我发现的所有方法对我的问题没有帮助。

我在Objective C中find了一个解决scheme,所以我把代码移植到了Swift(尽pipe你需要testing它):

 class testHandler: NSObject, NSURLConnectionDelegate{ func testURL(urlPath: String){ let url: NSURL = NSURL(string: urlPath)! let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "HEAD" let connection = NSURLConnection(request: request, delegate: self) } func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse){ if response is NSHTTPURLResponse{ if (response as! NSHTTPURLResponse).statusCode==200{ //url exists } } } } 

@sschale的答案很好,但NSURLConnection已被弃用,现在最好使用NSURLSession。

这是我的一个URLtesting类的版本:

 class URLTester { class func verifyURL(urlPath: String, completion: (isOK: Bool)->()) { if let url = NSURL(string: urlPath) { let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "HEAD" let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (_, response, error) in if let httpResponse = response as? NSHTTPURLResponse where error == nil { completion(isOK: httpResponse.statusCode == 200) } else { completion(isOK: false) } } task.resume() } else { completion(isOK: false) } } } 

你可以通过调用具有尾部闭包的类方法来使用它:

 URLTester.verifyURL("http://google.com") { (isOK) in if isOK { print("This URL is ok") } else { print("This URL is NOT ok") } } 

Swift 3.0与URLSession

 class URLTester { class func verifyURL(urlPath: String, completion: @escaping (_ isOK: Bool)->()) { if let url = URL(string: urlPath) { var request = URLRequest(url: url) request.httpMethod = "HEAD" let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in if let httpResponse = response as? HTTPURLResponse, error == nil { completion(httpResponse.statusCode == 200) } else { completion(false) } }) task.resume() } else { completion(false) } } } 

这比你的答案要好,因为它只下载响应标题,而不是整个页面(也因为asynchronous而更好)。

@Moritz提供的答案的Obj-C变体:

注:我喜欢一个function,而不是一个类,但行为是一样的:

 +(void)verifyURL:(NSString*)urlPath withCompletion:(void (^_Nonnull)(BOOL isOK))completionBlock { NSURL *url = [NSURL URLWithString:urlPath]; if (url) { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"HEAD"; //optional: request.timeoutInterval = 3; NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { BOOL isOK = NO; if ([response isKindOfClass:[NSHTTPURLResponse class]]) { int code = (int)((NSHTTPURLResponse*)response).statusCode; //note: you may want to allow other http codes as well isOK = !error && (code == 200); } completionBlock(isOK); }]; [dataTask resume]; } else { completionBlock(NO); } } 

这是一个带时间戳的电话:

 NSDate *date1 = [NSDate date]; [AppDelegate verifyURL:@"http://bing.com" withCompletion:^(BOOL isOK) { NSDate *date2 = [NSDate date]; if (isOK) { NSLog(@"url is ok"); } else { NSLog(@"url is currently not ok"); } NSTimeInterval diff = [date2 timeIntervalSinceDate:date1]; NSLog(@"time to return: %.3f", diff); }]; 

为了便于使用,我写了下面的代码,它的工作完美。

 var video_Url = "" if let url = NSURL(string: Response), data = NSData(contentsOfURL: url) { video_Url = Response } else { video_Url = "" }