gpt4 book ai didi

ios - 执行简单的 POST 请求 Swift

转载 作者:搜寻专家 更新时间:2023-11-01 07:26:24 25 4
gpt4 key购买 nike

我想用 Swift 执行小的 POST 请求,但我不知道该怎么做。这就是我使用 CURL 的方式:

curl --data "ime=YOURNAME&pitanje=YOURQUESTION" http://localhost/seka/postavi.php

如何在 Swift for iOS 中做到这一点?

最佳答案

非常简单的 RestApiManager 类,我认为它会对您有所帮助

typealias ServiceResponse = (JSON, NSError?) -> Void

class RestApiManager: NSObject {
static let sharedInstance = RestApiManager()

let baseURL = "http://api.randomuser.me/"

func getRandomUser(onCompletion: (JSON) -> Void) {
let route = baseURL
makeHTTPGetRequest(route, onCompletion: { json, err in
onCompletion(json as JSON)
})
}

func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)

let session = NSURLSession.sharedSession()

let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data)
onCompletion(json, error)
})
task.resume()
}

func makeHTTPPostRequest(path: String, body: [String: AnyObject], onCompletion: ServiceResponse) {
var err: NSError?
let request = NSMutableURLRequest(URL: NSURL(string: path)!)

// Set the method to POST
request.HTTPMethod = "POST"

// Set the POST body for the request
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(body, options: nil, error: &err)
let session = NSURLSession.sharedSession()

let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data)
onCompletion(json, err)
})
task.resume()
}

}

关于ios - 执行简单的 POST 请求 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35819486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com