objective c - Best practise to Use NSURLSession to receive data from the server on the background(not on the main theard) -


how receive data server(the server echo's json) using nsurlsession in efficient way?

example:

i'm trying use instagram's news feed save template. show 10 images , load 10 more(from server) when pull down , not block user (they receive/download on background - while users still using app).

i want same thing in efficient way. in example screen frozen until data fetched. how can avoid blocking user?

 var imgurl  = "http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg"         var sessionconfog =     nsurlsessionconfiguration.defaultsessionconfiguration()         var sessions : nsurlsession = nsurlsession(configuration: sessionconfog, delegate: nil, delegatequeue: nil)         var getimagetask = sessions.downloadtaskwithurl(nsurl(string: imgurl)!, completionhandler: { (location : nsurl!, response : nsurlresponse!, error : nserror?) -> void in             var image : uiimage = uiimage(data: nsdata(contentsofurl: location)!)!             dispatch_async(dispatch_get_main_queue(), { () -> void in                self.iamgeview.image = image                let m = self.saveimage(image, path: self.documentsdirectory())                println(m)             })         })         getimagetask.resume() 

edit:

i noticed, not using nsurlsession correctly! in completion block see this:

var image : uiimage = uiimage(data: nsdata(contentsofurl: location)!)! 

don't this. nsurlsession download task downloaded data you, don't have download again method 'contentsofurl'. method synchronous, , blocks calling thread until contents of url loaded. should never use method make network urls.

what need implement delegate methods download task data when completes. easier way use datataskwithurl:completionhandler - message, completion handler receives nsdata response.

end edit

you using nsurlsession correctly, if profile app, see expensive operation here, , 1 blocks ui thread, is:

let m = self.saveimage(image, path: self.documentsdirectory()) 

if can save image in separate serial queue, you'll see big improvement.


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -