简体   繁体   中英

How to get all the urls that contain specific string?

I need to get all the urls that end with ".jpg". My code:

func findPicUrl(url: NSURL){
    var error: NSError?
    var HTML = NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error)
    var detector = NSDataDetector(types: NSTextCheckingType.Link.rawValue, error: nil)
    var matches = detector!.matchesInString(HTML! as String, options: nil, range: NSMakeRange(0, HTML!.length))
    for match in matches {
        if (match as! NSString).containsString(".jpg"){
            println(match)
        }
    }
}

It prints all the urls without " if statement " but when i add " if statement " i get an error

"Could not cast value of type 'NSLinkCheckingResult' to 'NSString'"**.

How to solve it ?

You have to double unwrap the URL property from the NSLinkCheckingResult s, cast it as an NSURL then you can use the pathExtension property to find "jpg" images links:

for match in matches {
    if let temp = match.URL, matchURL = temp as NSURL! {
        if matchURL.pathExtension == "jpg" {
            println(matchURL.absoluteString!)
        }
    }
}

Replace your for loop code as below.

   for match in matches {
        if match.rangeOfString(".jpg") != nil{
           println("match")
       }
    }

The documentation says:

NSTextCheckingResult is a class used to describe items located by text checking. Each of these objects represents an occurrence of requested textual content that has been found during the analysis of a block of text.

For example NSTextCheckingResult has a range property which contains the range of the matching string in the HTML variable.

Try this

var error: NSError?
if let HTML = NSString(contentsOfURL: NSURL(string:"http://macfix.de")!, encoding: NSUTF8StringEncoding, error: &error) {
  let detector = NSDataDetector(types: NSTextCheckingType.Link.rawValue, error: nil)
  let matches = detector!.matchesInString(HTML as String, options: nil, range: NSMakeRange(0, HTML.length))
  for match in matches {
    let HTMLmatch = (HTML as NSString).substringWithRange(match.range)
    if HTMLmatch.rangeOfString("jpg") != nil {
      println(HTMLmatch)
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM