Bishan
Bishan

Reputation: 401

How to check the content availability of a URL

I'm creating a app which has a UITableView. When the user selects one row, it transitions to a content page that has an image slider and its content. There can be minimum of 0 and maximum of 4 images per item.

When loading the inner page, I'm checking the image availability using this method:

func validateUrl (stringURL : NSString) -> Bool {

    let url = NSURL(string: stringURL as String)
    if (NSData(contentsOfURL: url!) ==  nil){
        return false
    }
    else{
        return true
    }

} 

It's a really simple method to get the proper output and it always works, but it takes lot of time and because of it I have to load images twice (one for this method and second time to display them).

Is there any better way to do this?

Upvotes: 0

Views: 129

Answers (2)

Chiko
Chiko

Reputation: 606

I would add to this method some code to catch the data that was received from

NSData(contentsOfURL: url!)

For example a map with the url as key and data as object. this way, to display the picture you first check the map and only if it's not there you download it

Upvotes: 1

Jorgesys
Jorgesys

Reputation: 126445

try:

if let data = NSData(contentsOfURL: url) {
     return true
}else{
     return false
}

Upvotes: 0

Related Questions