使用Swift将数据发布到服务器

时间:2018-04-02 12:02:21

标签: ios swift xcode post

在swift中,我几天来一直面临这个问题,我不知道我在这里开始的错误是我的viewcontroller.swift

import UIKit
import Foundation
var otp=0

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,UITextFieldDelegate
,HomeModelProtocol{


    @IBOutlet weak var nameField: UITextField!

    @IBOutlet weak var dobField: UITextField!

    @IBOutlet weak var genderField: UITextField!

    @IBOutlet weak var phoneField: UITextField!

    @IBOutlet weak var emailField: UITextField!



    //Properties

    var feedItems: NSArray = NSArray()
    var selectedLocation : LocationModel = LocationModel()

    @IBOutlet weak var listTableView: UITableView!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        //set delegates and initialize homeModel

        //self.listTableView.delegate = self
        //self.listTableView.dataSource = self

       let homeModel = HomeModel()
        homeModel.delegate = self as HomeModelProtocol
        homeModel.downloadItems()




       /* do
        {
            self.dobField.delegate = self
        }
        catch {
            print("empty")
        }
        do
        {
        self.emailField.delegate = self
        }
        catch{
            print("Empty")
        }
        do{   self.nameField.delegate = self
        }
        catch{

            print("Empty")
        }
        do{

            self.genderField.delegate = self
        }
        catch{
            print("Empty")
        }

            do
            {
            self.phoneField.delegate = self
        }
            catch{
                print("Empty")

        }*/
        }

    func itemsDownloaded(items: NSArray)
    {

        feedItems = items
        //self.listTableView.reloadData()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        // Return the number of feed items
        return feedItems.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {

        // Retrieve cell
        let cellIdentifier: String = "BasicCell"
        let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
        // Get the location to be shown
        let item: LocationModel = feedItems[indexPath.row] as! LocationModel
        // Get references to labels of cell
        myCell.textLabel!.text = item.countryname

        return myCell
    }




    @IBAction func onPostTapped2(_ sender: Any)

    {


        /*let parameters = ["name": "Lakshmi ILLe", "dob": "1234567890","gender": "Male","email": "Laksmhi@gmail.com","password":"iamille","contact": "1234567890"]*/
        /*let parameters = "name=ALoke Nath"
        guard let url = URL(string: "http://192.168.85.115/assignment5/public/dataInsert") else { return }
        var request = URLRequest(url: url)
        request.httpMethod = "POST"

       request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, 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()
        */


        let name = nameField.text!
        let dob = dobField.text!
        let gender = genderField.text!
        let phone = phoneField.text!
        let email = emailField.text!
        let password=phoneField.text!
        let contact = phoneField.text!
        let countryId=2
        let data = Data()
        let headers = [
            "content-type": "application/x-www-form-urlencoded",
            "cache-control": "no-cache"
        ]

        print(headers)
        let postData = NSMutableData(data: ("name="+String(name)).data(using: String.Encoding.utf8)!)

        postData.append(("&dob="+String(dob)).data(using: String.Encoding.utf8)!)

        postData.append(("&gender="+String(gender)).data(using: String.Encoding.utf8)!)
        postData.append(("&email="+String(email)).data(using: String.Encoding.utf8)!)
        postData.append(("&password="+String(phone)).data(using: String.Encoding.utf8)!)
        postData.append(("&contact="+String(phone)).data(using: String.Encoding.utf8)!)
        postData.append(("&countryId=2").data(using: String.Encoding.utf8)!)



        print(postData)
        let requestnew = NSMutableURLRequest(url: NSURL(string: "http://192.168.85.115/assignment5/public/dataInsert")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        requestnew.httpMethod = "POST"
        requestnew.allHTTPHeaderFields = headers
        requestnew.httpBody = postData as Data

        print(requestnew.httpBody!)

        let sessionnew = URLSession.shared
        let dataTasknew = sessionnew.dataTask(with: requestnew as URLRequest, completionHandler: { (data, responsenew, errornew) -> Void in
            if (errornew != nil) {
                print(errornew!)
            } else {
                let httpResponsenew = responsenew as? HTTPURLResponse
                print(httpResponsenew!)
                //print(data!)
            }


        })




       let A: UInt32 = 100000
        let B: UInt32 = 999999
        otp  = Int(arc4random_uniform(B - A + 1) + A)
        print(otp)



        dataTasknew.resume()

    }

    @IBOutlet weak var otpField: UITextField!

    @IBAction func Otptapped(_ sender: Any) {
        print(otp)
        let otp2=Int(otpField.text!)

        print(otp2!)

        if otp2==otp{
            print("Verified")
        }
            else{
                print("Recheck otp")
            }

    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return(true)
    }






}

在尝试将数据提交到位于URL的服务器时,我不断得到这个错误,这对我来说是个胡言乱语

第一部分我打印了标题和附加的postdata 但最后当响应部分给了我laravel_session的东西时,我不清楚

//此标题

["cache-control": "no-cache", "content-type": "application/x-www-form-urlencoded"]

//这是postdata

<6e616d65 3d616263 26646f62 3d343537 38373738 37393626 67656e64 65723d4d 616c6526 656d6169 6c3d7177 65406665 642e636f 6d267061 7373776f 72643d37 38353437 34313132 3326636f 6e746163 743d3738 35343734 31313233 26636f75 6e747279 49643d32>

104个字节 //这是otp不需要或发送

855494

//这是回复

<NSHTTPURLResponse: 0x604000231620> { URL: http://192.168.85.115/assignment5/public/dataInsert } { status code: 400, headers {
    "Cache-Control" = "no-cache";
    Connection = close;
    "Content-Type" = "application/json";
    Date = "Mon, 02 Apr 2018 11:48:01 GMT";
    Server = "Apache/2.4.29 (Win32) OpenSSL/1.0.2n PHP/5.6.33";
    "Set-Cookie" = "laravel_session=eyJpdiI6IldEdFFscW1WcTRDcGdTZDBHcUxuSlE9PSIsInZhbHVlIjoiVDBwRkl4b2tISm5CbEdLQkJOdTZOYytzMFRIVWZRK1QyVXRRWkp1OVhuZkJCNXQxODlwTkp3S1lzNmpjaFc0QjlHT2R1dkFVZXdCd1B1MWFINDVmeHc9PSIsIm1hYyI6IjI5OTE3MWNjMzJjYjNiZDcxZTE1Mjc0OGE5OGY5ZGZhMjQwNTI2NmVlOWEwNTA4NDg2MTk2MjM5YjBkNjdjN2QifQ%3D%3D; expires=Mon, 02-Apr-2018 13:48:01 GMT; Max-Age=7200; path=/; httponly";
    "Transfer-Encoding" = Identity;
    "X-Powered-By" = "PHP/5.6.33";
} }

13819 bytes
Data downloaded
13819 bytes

Xcode:9.0 斯威夫特:4.0

请帮忙!

3 个答案:

答案 0 :(得分:0)

你可以使用Alamofire: -

Github链接: - Alamofire

func Loaddata()
{
    let strUrl = "http://192.168.85.115/assignment5/public/dataInsert"
    let parameter:Parameters = ["name": "Lakshmi ILLe", "dob": "1234567890","gender": "Male","email": "Laksmhi@gmail.com","password":"iamille","contact": "1234567890"]
    Alamofire.request(strUrl, method : .post, parameters: parameter).responseJSON{response in
       let result = response.result
       print(result)
      }
}

您将在此处获得回复。

答案 1 :(得分:0)

func ServiceCall(url: String, Parameters: String, Method: String, Completion: @escaping(_ dictionary: Any?, _ error: Error?)-> Void) {

        DispatchQueue.global(qos: .background).async {

            var request = URLRequest(url: URL(string: url)!) // add your url here
            request.httpMethod = Method // Method  GET/POST

            let param = Parameters.data(using: .utf8) // Parameters to pass to server
            request.httpBody = param
            print("task created")
            let task = URLSession.shared.dataTask(with: request){ data, response, error in

                guard let _ = data, error == nil else{
                    print("Error : \(String(describing: error))")
                    Completion(nil,error)
                    return
                }

                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(String(describing: response))")
                    // make error here and then
                    Completion(nil, error)
                    return
                }

                DispatchQueue.main.async {
                    do{
                        let jsonReponse = try JSONSerialization.jsonObject(with: data!, options: [])
                        Completion(jsonReponse,nil)
                    }
                    catch{
                        Completion(nil, error)
                    }
                }
            }
            task.resume()

        }
    }

通过调用上述函数,您将在完成处理程序中获得响应和错误(如果有)。

答案 2 :(得分:-1)

使用以下代码将您的json对象转换为Dictionary

let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]