ios - How to call REST service in Swift 3.0 -
i need call simle rest client https://httpbin.org/ip , paste json result label field in ios device. i'm writing in xcode 8.0, , swift version 3.0. found many tutorials, of them written older versions of swift. compiler failing , cannot fix it. seems newer version have significant changes. can please provide working example. appreciated lot. thanks.
in example expecting see rest invocation , reading result.
you can try this, works well.
@iboutlet weak var iplabel: uilabel! override func viewdidload() { super.viewdidload() let parsedata = parsejson(getjson("https://httpbin.org/ip")) let ipvalue = parsedata.valueforkey("origin") self.performselectoronmainthread(#selector(viewcontroller.updateiplbl(_:)), withobject: ipvalue, waituntildone: false) } func getjson(urltorequest:string) -> nsdata { return nsdata(contentsofurl: nsurl(string: urltorequest)!)! } func parsejson(inputdata:nsdata) -> nsdictionary{ let dictdata = (try! nsjsonserialization.jsonobjectwithdata(inputdata, options: .mutablecontainers)) as! nsdictionary return dictdata } func updateiplbl(text: string) { self.iplabel.text = "your ip " + text }
Comments
Post a Comment