ios – 如何在Swift中创建NSURLSession POST请求

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

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

BackGroundClass: –

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)
    }
}

视图控制器: –

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.0发布示例 –
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,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()
    }

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...