我一直在尝试使用 Swift 为移动应用程序打印和 HTTP 发布,我可以使用 javascript 和 express.js 记录它。但是当使用用 Go 创建的服务器时,它给了我:
Get "http://192.121.1.397:8080": dial tcp http://192.121.1.397:8080: i/o timeout
exit status 1
您可以在下面看到所有 3 种语言的代码:
迅速:
import Foundation
class Service: NSObject {
static let shared = Service()
func fetch(completion: @escaping (Result<[Post], Error>) -> ()){
guard let url = URL(string: "http://192.121.1.397:8080" ) else{return}
URLSession.shared.dataTask(with: url) { (data, resp, err) in
if let err = err {
print(err)
return
}
guard let data = data else {return}
do{
let posts = try JSONDecoder().decode([Post].self, from:data)
completion(.success(posts))
} catch{
completion(.failure(error))
}
}
}
func post(title: String, body: String, completion: @escaping (Error?) -> ()) {
guard let url = URL(string: "http://192.168.1.148:8080") else{return}
var urlReq = URLRequest(url:url)
urlReq.httpMethod = "POST"
let params = ["title": title, "postBody": body]
do{
let data = try JSONSerialization.data(withJSONObject: params, options: .init())
urlReq.httpBody = data
urlReq.setValue("application/json", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(with: urlReq){(data, resp, err) in
guard let data = data else{return}
completion(nil)
}.resume()
} catch{
completion(error)
}
}
}
守着一只汪
相关分类