HTTP Requests in Swift 3

前端 未结 3 1104
终归单人心
终归单人心 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条回答
  •  -上瘾入骨i
    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
    

提交回复
热议问题