Search code examples
iosswift2nstimernsdata

How to set time limit of function?


In my project I am accessing images from URL. In these URLs I gave 2-3 dummy URL which doesn't have any data. But my code takes more time to access & identifies that there is no imageData on the url. Here is the code

func callImageURL(urlString : String) -> UIImage
{


    // define an image
    var contentImage : UIImage = UIImage(named: "defaultImage.jpg")!

    // convert String url to NSURL
    let url = NSURL(string: urlString)

    // if url exist
    if (url != nil)
    {
        // fetch the imageData from url
        let data = NSData(contentsOfURL: url!)

        // if image data exist
        if (data != nil)
        {
            // convert imagedata back to an image
            contentImage = UIImage(data: data!)!
        }
    }


    return contentImage
}

So my question is that how can I put execution time limit on my code. OR Is there any way by which I can make my code more efficient?


Solution

  • If you have some time consuming functions, you can call them in background thread and then update UI on main thread. Code example:

    func callImageURL(urlString : String, completion: UIImage -> Void) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            var contentImage = UIImage(named: "defaultImage.jpg")
    
            if let url = NSURL(string: urlString), data = NSData(contentsOfURL: url)  {
                contentImage = UIImage(data: data)
            }
    
            dispatch_async(dispatch_get_main_queue()) {
                completion(contentImage!)
            }
        }
    }
    
    callImageURL("your url") {image in
        //Use your image
    }