ios - Old Swift to Swift 3 -


a while created function take json , print terminal. worked 2 years ago when have copied in latest project full of errors :/ have resolved of them still have 2 outstanding issues follows:

var arr = jsonserialization.jsonobjectwithdata(data!, options: nil, error: nil) as! nsarray 

the above line complains "extra argument 'error' in call.

for var = 0 ; < (arr nsarray).count ; += 1 

the above line says "c-style statement has been removed in swift 3"

any on resolving these 2 great.

full function code below:

func jsonparsing() {      let prefs:userdefaults = userdefaults.standard     var webaddress = prefs.value(forkey: "webaddress") as! string       let url2 = url(string: webaddress + "straightred/jsonfixture/")      let data = try? data(contentsof: url2!)      var arr = jsonserialization.jsonobjectwithdata(data!, options: nil, error: nil) as! nsarray      arrdict = []      var = 0 ; < (arr nsarray).count ; += 1     {         arrdict.addobject((arr nsarray) .objectatindex(i))     }      print(arrdict);  } 

first of all, do not use nsarray in swift, use swift native collection types.

second of all, do not load data synchronously remote url, use urlsession

third of all, don't need loop, assign received array arrdict

  • declare arrdict swift array of dictionaries

    var arrdict = [[string:any]]() 
  • this code uses proper method of userdefaults , do - catch block, options parameter of jsonobject(with can omitted.

    func jsonparsing() {     let prefs = userdefaults.standard     let webaddress = prefs.string(forkey: "webaddress")!     let url2 = url(string: webaddress + "straightred/jsonfixture/")!      let task = urlsession.shared.datatask(with: url2) { [unowned self] (data, response, error) in         if let error = error {             print(error)             return         }         {             let arr = try jsonserialization.jsonobject(with:data!) as! [[string:any]]             self.arrdict = arr             print(self.arrdict)          } catch {             print(error)         }     }     task.resume() } 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

angular - Copying node modules to wwwroot AspNetCore -