how to check if rtmp or hls urls are exist or they'll give 404 error in swift

前端 未结 4 674
暖寄归人
暖寄归人 2020-12-18 11:24

I need to parse some data from rss and open related links from parsed rss in swift 2, for example i want to check this link is valid or not:

rtmp://185.23.1         


        
4条回答
  •  攒了一身酷
    2020-12-18 11:52

    The answer by @sschale is nice, but NSURLConnection is deprecated, it's better to use NSURLSession now.

    Here's my version of an URL testing class:

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

    And you use it by calling the class method with a trailing closure:

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

    Swift 3.0 with 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)
        }
      }
    }
    

    This is better than your answer because it only downloads the response headers instead of the whole page (also, it's better because asynchronous).

提交回复
热议问题