如何检查rtmp或hls url是否存在或者他们会在swift中给出404错误

ano*_*mox 3 validation url rss ios swift2

我需要从rss解析一些数据并从swift 2中解析的rss打开相关链接,例如我想检查此链接是否有效:

rtmp://185.23.131.187:1935/live/jomhori1
Run Code Online (Sandbox Code Playgroud)

或者这个:

http://185.23.131.25/hls-live/livepkgr/_defint_/liveevent/livestream.m3u8
Run Code Online (Sandbox Code Playgroud)

我的代码检查url的验证:

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
                            }
Run Code Online (Sandbox Code Playgroud)

我搜索过网络,但我找到的所有方法对我的问题没有帮助.

aya*_*aio 5

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

这是我的URL测试类版本:

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)
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

并通过使用尾随闭包调用类方法来使用它:

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

带有URLSession的Swift 3.0

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)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这比你的答案更好,因为它只下载响应头而不是整个页面(同样,它更好,因为异步).