swift - how build objects with alamofire and SwiftyJSON -


i'm trying create app returns multi-up table many data think need completion handler in here.

// object data :  import foundation  class  reposwiftyjson:nsobject {     let _userid:string!    let _title:string!     init(userid:string , title:string){       self._userid = userid       self._title = title      } } 

tableviewcontroller

import uikit import alamofire import swiftyjson  class tableviewcontroller: uitableviewcontroller {      var parkdata:[json] = []    var aryid = [reposwiftyjson]()     func getjsondata() {        let url = "http://jsonplaceholder.typicode.com/posts/"         alamofire.request(.get,url).responsejson {response in            guard let data = response.result.value else {                let error = response.result.error                 let alertcontroller = uialertcontroller(title: "error", message:error?.localizeddescription, preferredstyle: .alert)                let okaction = uialertaction(title: "retry", style: .default, handler: { (alert:uialertaction) -> void in                       uiapplication.sharedapplication().networkactivityindicatorvisible = true                       self.getjsondata()                       alertcontroller.dismissviewcontrolleranimated(true, completion: {})                })                 alertcontroller.addaction(okaction)                self.presentviewcontroller(alertcontroller, animated: true, completion: {})                uiapplication.sharedapplication().networkactivityindicatorvisible = false                return            }             let json = json(data)            self.parkdata = json.array!             key in self.parkdata{               let dataarray:reposwiftyjson = reposwiftyjson ()               let userid = key["userid"].intvalue               let title = key["title"].string               dataarray._userid = userid               dataarray._title = title               self.aryid.append(dataarray)            }            self.showjsondata()       }     }     func showjsondata() {       //println(parkdata)       tableview.reloaddata()    }     override func viewdidload() {      super.viewdidload()      getjsondata()    }      // mark: - table view data source     override func numberofsectionsintableview(tableview: uitableview) -> int {       return 1    }     override func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int {         if let numberofrows: int = self.aryid.count {           return numberofrows        } else {           return 0        }         }      override func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell {        let cell = tableview.dequeuereusablecellwithidentifier("mastercell", forindexpath: indexpath)          let rowdata:json = aryid[indexpath.row]        cell.textlabel?.text = rowdata._title        cell.detailtextlabel?.text = string(rowdata._userid)        print(rowdata)        return cell     } 

but when run app following error:

missing argument parameter 'userid'  

in line call line let dataarray:reposwiftyjson = reposwiftyjson ()

and

cannot subscript value of type '[reposwiftyjson]'  

in line let rowdata:json = aryid[indexpath.row]

what i'm doing wrong?

let's fix issues parts:

first error:

according apple:

classes , structures must set of stored properties appropriate initial value time instance of class or structure created. stored properties cannot left in indeterminate state.

you can set initial value stored property within initializer, or assigning default property value part of property’s definition.

you're trying use default init method in class reposwiftyjson inherits nsobject, it's not recommend use ! operator explicit compiler object going have value in runtime. 1 option solve problem use convenience initializer in following way:

class reposwiftyjson: nsobject {     let _userid: string    let _title: string     init(userid:string , title:string){       self._userid = userid       self._title = title    }     override convenience init() {      self.init(userid: "a", title: "b")    } }  let dataarray: reposwiftyjson = reposwiftyjson() dataarray._title // dataarray._userid // b 

in above way override default init of class nsobject , mark convenience allow call init(userid:string , title:string) inside default init method.

there many ways of solve first error, above one.

second error:

if check variable aryid in definition :

var aryid = [reposwiftyjson]() 

it's array of reposwiftyjson, , in following line:

let rowdata: json = aryid[indexpath.row] 

you're trying assign element of type reposwiftyjson returned above line of type json , it's not correct.

edit:

you can create json using following function:

let jsonobject: [anyobject] = [    ["name": "john", "age": 21],    ["name": "bob", "age": 35], ]  func createjson(value: anyobject) -> string {     let options = nsjsonwritingoptions.prettyprinted     guard nsjsonserialization.isvalidjsonobject(value) else {       return ""    }     {        let data = try nsjsonserialization.datawithjsonobject(value, options: options)         if let string = nsstring(data: data, encoding: nsutf8stringencoding) {           return string string        }    } catch let error {        print("\(error)")    }    return "" }   let json = createjson(jsonobject) 

and see :

[   {     "age" : 21,     "name" : "john"   },   {     "age" : 35,     "name" : "bob"   } ] 

i hope you.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -