HTTP Requests in Swift 3

前端 未结 3 1110
终归单人心
终归单人心 2021-02-14 05:17

I am fairly new to Swift, and am trying to make an HTTP request. I tried many of the ideas in this Stack Overflow question, but all caused errors when run in a playground; I bel

3条回答
  •  春和景丽
    2021-02-14 05:46

    There are a couple problems with your code:

    1. By default, your app cannot connect to insecure (i.e. HTTP) site. It's a feature called App Transport Security. You need to make an exception in your app's Info.plist file to connect to HTTP sites.
    2. This: dataTask(urlwith: ! as URL). What are you trying to unwrap with the exclamation mark (!)? What's the variable name?

    A lot of class names have changed between Swift 2 and 3 so those answers you've found may not be applicable. Below is an example that connects to httpbin.org to get your IP address:

    import PlaygroundSupport
    import Foundation
    
    let url = URL(string: "https://httpbin.org/ip")
    
    let task = URLSession.shared.dataTask(with: url!) { data, response, error in
        guard error == nil else {
            print(error!)
            return
        }
        guard let data = data else {
            print("Data is empty")
            return
        }
    
        let json = try! JSONSerialization.jsonObject(with: data, options: [])
        print(json)
    }
    
    task.resume()
    PlaygroundPage.current.needsIndefiniteExecution = true
    

提交回复
热议问题