gpt4 book ai didi

ios - 在 iOS Swift 中执行 POST 请求

转载 作者:可可西里 更新时间:2023-10-31 23:57:19 25 4
gpt4 key购买 nike

我正在尝试执行 POST 请求,但请求没有通过。我已经看过 Perform POST request in Swift已经,但它不包含我正在寻找的内容。

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
var request = NSMutableURLRequest(URL: NSURL(string: "https://us1.lacunaexpanse.com"))
println("request url https://us1.lacunaexpanse.com")
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

let apikey = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
println("apikey",apikey)

let username = "username"
let password = "password"

var login = Array(["username", "password", "apikey"])

let jsonDictionary = ["2.0", "jsonrpc", "1", "id", "login", "method", "login", "params"]
println("jsonDictionary",jsonDictionary)

var writeError: NSError?

let jsonData = NSJSONSerialization.dataWithJSONObject(jsonDictionary, options: NSJSONWritingOptions(), error: NSErrorPointer())

var resultAsString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)

resultAsString = resultAsString.stringByAppendingString("empire")

let url = NSURL.URLWithString("string")
println("url",url)

var request2 = NSMutableURLRequest()
println("Post url =%@",url)

request2 = NSMutableURLRequest(URL:url)

request2.HTTPMethod = "POST"

var connection = NSURLConnection(request: request, delegate: self, startImmediately: false)

return true

最佳答案

这里有一大堆战术问题:

  1. 您正在创建 URLSession,然后发出 NSURLConnection 请求。只需使用 URLSession

  2. 您的“请求字典”不是字典,而是数组。例如发出JSON-RPC请求,字典的正确格式是:

    let requestDictionary: [String: Any] = [
    "jsonrpc" : "2.0",
    "id" : 1,
    "method" : "login",
    "params" : ["myuserid", "mypassword", "mykey"]
    ]
  3. 小问题,但是您使用了很多变量(通过 var),而常量(通过 let)就可以了。本着 Swift 的安全精神,尽可能使用 let

  4. 根据 Lacuna Expanse API ,您的 URL 应该包含模块名称。

    因此,例如,如果在“Empire”模块中执行POST 请求,则URL 是:

    let url = URL(string: "https://us1.lacunaexpanse.com/empire")!
  5. 您可能会执行大量请求,因此我建议将大部分请求放在一个可以反复调用的函数中,而无需到处重复代码。也许像下面这样的函数采用以下参数:

    • 模块(例如“帝国”与“联盟”);

    • 方法(例如“登录”与“获取验证码”);

    • 适合该请求的参数(例如,对于“登录”,这将是“名称”、“密码”和“api_key”);和

    • 将在异步请求完成时调用的闭包。

    此函数然后准备 JSON-RPC 请求并在请求完成时调用闭包:

    @discardableResult
    func submitLacunaRequest(module: String, method: String, parameters: Any, completion: @escaping (Result<[String: Any], Error>) -> Void) -> URLSessionTask? {
    let session = URLSession.shared
    let url = URL(string: "https://us1.lacunaexpanse.com")!
    .appendingPathComponent(module)
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json-rpc", forHTTPHeaderField: "Content-Type")

    let requestDictionary: [String: Any] = [
    "jsonrpc": "2.0",
    "id" : 1,
    "method" : method,
    "params" : parameters
    ]

    request.httpBody = try! JSONSerialization.data(withJSONObject: requestDictionary)

    let task = session.dataTask(with: request) { data, response, error in

    // handle fundamental network errors (e.g. no connectivity)

    guard error == nil, let data = data else {
    completion(.failure(error ?? URLError(.badServerResponse)))
    return
    }

    // check that http status code was 200

    guard
    let httpResponse = response as? HTTPURLResponse,
    200 ..< 300 ~= httpResponse.statusCode
    else {
    completion(.failure(URLError(.badServerResponse)))
    return
    }

    // parse the JSON response

    do {
    guard let responseObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
    throw URLError(.badServerResponse)
    }
    completion(.success(responseObject))
    } catch let parseError {
    completion(.failure(parseError))
    }
    }
    task.resume()

    return task
    }

    这会在 JSON-RPC 请求中对方法和参数进行所有必要的包装。然后,您需要做的就是调用该方法:

    submitLacunaRequest(module: "empire", method: "login", parameters: ["myuserid", "mypassword", "mykey"]) { result in

    switch result {
    case .failure(let error):
    print("error = \(error)")

    case .success(let value):
    if let errorDictionary = value["error"] as? [String: Any] {
    print("error logging in (bad userid/password?): \(errorDictionary)")
    } else if let resultDictionary = value["result"] as? [String: Any] {
    print("successfully logged in, refer to resultDictionary for details: \(resultDictionary)")
    } else {
    print("we should never get here")
    print("responseObject = \(value)")
    }
    }
    }

    对于需要字典的请求,例如“创建”,只需提供字典即可:

    submitLacunaRequest(module:"empire", method: "create", parameters: [
    "name" : "user",
    "password" : "password",
    "password1" : "password",
    "captcha_guid" : "305...dd-....-....-....-e3706...73c0",
    "captcha_solution" : "42",
    "email" : "test@gmail.com"
    ]) { result in
    switch result {
    case .failure(let error):
    print("error = \(error)")

    case .success(let value):
    print("responseObject = \(responseObject)")
    }
    }

很明显,在上面这些中,我只是做了最少的错误处理,所以你可以加强这个,但你的问题是关于发出 POST 请求,希望上面说明了这是如何完成的。

有关 Swift 2 版本,请参阅 previous revision这个答案。

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

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