json - Data taking too long to load when loading UITableView from a NSURLConnection -
my app displays information stored on our server, updated constantly. therefore when browsing data load each page data retrieved using following class
public class getremotedata { class func getdatafromserver(success: ((svrdata: nsdata!) -> void)) { //set http connection settings let httpmethod = "get" let timeout = 10 let url = nsurl(string: viewcontroller.gvariables.gurl) let urlrequest = nsmutableurlrequest(url: url!, cachepolicy: .reloadignoringlocalandremotecachedata, timeoutinterval: 10.0) let queue = nsoperationqueue() //initiate connection server nsurlconnection.sendasynchronousrequest( urlrequest, queue: queue, completionhandler: {(response: nsurlresponse!, data: nsdata!, error: nserror!) in //if data recieved load svrdata if data.length > 0 && error == nil{ let json = nsstring(data: data, encoding: nsasciistringencoding) if let urldata = json { let data = json!.datausingencoding(nsutf8stringencoding) success(svrdata: data) } }else if data.length == 0 && error == nil{ viewcontroller.gvariables.gerror = "no data recieved, please check connection" } else if error != nil{ viewcontroller.gvariables.gerror = "error occurred - \(error), please check connection" } } ) } }
the data loads lot of time moving between viewcontrollers use class particularly when moving backwards first pass through drops through sendasynchronousrequest without success. viewcontroller carry on , displays blank table. above code runs on thread again time , data appears can take 30 seconds! code below used viewcontroller in viewdidload
getremotedata.getdatafromserver { (svrdata) -> void in let jsondict = nsjsonserialization.jsonobjectwithdata(svrdata, options: nil, error: nil) as! nsdictionary if (viewcontroller.gvariables.gerror != "") { let alertcontroller = uialertcontroller(title: "warning", message: viewcontroller.gvariables.gerror, preferredstyle: uialertcontrollerstyle.alert) alertcontroller.addaction(uialertaction(title: "ok", style: uialertactionstyle.default,handler: nil)) alertcontroller.presentviewcontroller(alertcontroller, animated: true, completion: nil) } if let items = jsondict["products"] as? nsarray { jsonitem in items { if let name = jsonitem.valueforkey("name") as? string { self.brandnames.addobject(name) } if let code = jsonitem.valueforkey("code") as? string { self.brandcodes.addobject(code) } } } self.tableview.reloaddata() }
could please tell me how can overcome time delay issue
both of above responses resolved problem enabling json code run on main thread
Comments
Post a Comment