HTTP Requests in Swift 3

2019-03-25 08:54发布

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 believe this is because they are all in Swift 1.0-2.0.

How can I make an HTTP request in Swift 3?

Update I tried the first solution presented in this answer and, after completing Xcode's suggested "Fix-its" I encountered four errors:

enter image description here

3条回答
小情绪 Triste *
2楼-- · 2019-03-25 09:25

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
查看更多
forever°为你锁心
3楼-- · 2019-03-25 09:27

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.

查看更多
Explosion°爆炸
4楼-- · 2019-03-25 09:28

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
查看更多
登录 后发表回答