How to call a REST service in Swift 3.0

I need to call simle rest client https://httpbin.org/ip and paste the JSON result in the label field on the iOS device. I am writing in Xcode 8.0 and Swift version 3.0. I found many tutorials, but they are all written for older versions of Swift. The compiler does not work, and I can not fix it. The newer version seems to have significant changes. Can anyone point out a working example. Will be appreciated a lot. Thank.

In this example, I expect to see a REST call and read the result.

+4
source share
1 answer

You can try this, it 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 is " + text
        }
+1
source

Source: https://habr.com/ru/post/1655463/


All Articles