HTTP Requests in Swift 3

前端 未结 3 1096
终归单人心
终归单人心 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
    
    0 讨论(0)
  • 2021-02-14 05:49

    There's typo errors (no url variable in the call) in your code.

    Anyway, in Swift 3 it's better to use the new URL struct and the URLSession class.

    Also, XCPlayground is now PlaygroundSupport.

    And no need to use NSString when String is available.

    import PlaygroundSupport
    PlaygroundPage.current.needsIndefiniteExecution = true
    
    let url = URL(string: "http://stackoverflow.com/")
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if let data = data,
            html = String(data: data, encoding: String.Encoding.utf8) {
                print(html)
        }
    }
    task.resume()
    

    Note: this is for Xcode 8 beta 2. On beta 1 you would have to do shared() instead of shared. If you're on iOS don't forget to import UIKit, but this code also works for OS X if you import Cocoa instead.

    0 讨论(0)
  • 2021-02-14 05:55

    In your error it seems url missing.Here bare simple api call to help you get started with.

    import UIKit
    import Foundation
    import PlaygroundSupport
    
    let url:URL = URL(string: "http://jsonplaceholder.typicode.com/posts")!
    let session = URLSession.shared
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
    
    let paramString = "data=Hello"
    request.httpBody = paramString.data(using: String.Encoding.utf8)
    
    let task = session.dataTask(with: request as URLRequest) {
        (
        data, response, error) in
    
        guard let data = data, let _:URLResponse = response  where error == nil else {
            print("error")
            return
        }
    
        let dataString =  String(data: data, encoding: String.Encoding.utf8)
        print(dataString)
    
    }
    
    task.resume()
    
    PlaygroundPage.current.needsIndefiniteExecution = true
    
    0 讨论(0)
提交回复
热议问题