gpt4 book ai didi

ios - 如何在 Swift 中发出 NSURLSession POST 请求

转载 作者:IT王子 更新时间:2023-10-29 05:14:57 30 4
gpt4 key购买 nike

嗨,我是 Swift 的初学者,我正在尝试让 NSURLSession“发布”请求发送一些参数,如下面的代码

根据我下面的代码响应不是来自服务器,请有人帮助我

背景类:-

 import UIKit

protocol sampleProtocal{

func getResponse(result:NSDictionary)
func getErrorResponse(error:NSString)
}

class BackGroundClass: NSObject {

var delegate:sampleProtocal?

func callPostService(url:String,parameters:NSDictionary){


print("url is===>\(url)")

let request = NSMutableURLRequest(URL: NSURL(string:url)!)

let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

//Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])

let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}

do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("Response: \(json)")
self.mainResponse(json)
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
self.eroorResponse(jsonStr!)
}
} catch let parseError {
print(parseError)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
self.eroorResponse(jsonStr!)
}
}

task.resume()
}

func mainResponse(result:NSDictionary){
delegate?.getResponse(result)
}

func eroorResponse(result:NSString){
delegate?.getErrorResponse(result)
}
}

View Controller :-

import UIKit

class ViewController: UIViewController,sampleProtocal {

override func viewDidLoad() {
super.viewDidLoad()

let delegate = BackGroundClass();
delegate.self;

let params = ["scancode":"KK03799-008", "UserName":"admin"] as Dictionary<String, String>

let backGround=BackGroundClass();
backGround.callPostService("url", parameters: params)
}

func getResponse(result: NSDictionary) {
print("Final response is\(result)");
}

func getErrorResponse(error: NSString) {
print("Final Eroor code is\(error)")
}
}

最佳答案

Swift 4 发布带有 json 负载的示例-

func postAction(_ sender: Any) {
let Url = String(format: "your url")
guard let serviceUrl = URL(string: Url) else { return }
let parameterDictionary = ["username" : "Test", "password" : "123456"]
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
return
}
request.httpBody = httpBody

let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
}

关于ios - 如何在 Swift 中发出 NSURLSession POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41997641/

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