Xcode func在另一个View Controller中使用

时间:2017-08-23 19:04:14

标签: mysql swift database xcode func

我在Swift文件中有这个func,它返回数据库中数据的值并将其打印出来。 我想在其他View Controller中使用该值,但我无法使其工作,所以我希望有人可以帮助我。 我希望在其他View Controller中使用private void Funky() { DataColumn RealDate = new DataColumn("RealDate"); RealDate.DataType = System.Type.GetType("System.DateTime"); dt.Columns.Add(RealDate); // strongly type a DateTime Column it will save you alot of problems in the future for (int i = 0; i < dt.Rows.Count; i++) { string[] temp = dt.Rows[i]["BirthDay"].ToString().Split('/'); dt.Rows[i]["RealDate"] = new DateTime(int.Parse(temp[0]), int.Parse(temp[1]), int.Parse(temp[2])); } // finaly get you result var targetDate = new DateTime(20, 5, 1994); DataTable FilterDt = dt.AsEnumerable().Where(x => x.Field<DateTime>("RealDate") < targetDate).Select(y => y).CopyToDataTable(); dataGridView1.DataSource = FilterDt; } nameUserstatusUser

pointUser

Hi Woof这就是我在viewcontroler中所拥有的:

 import Foundation
  import UIKit
  var code = "100"
  var getStatusUSer = ""

class getJSON: NSObject, URLSessionDataDelegate
{
//properties
var data : NSMutableData = NSMutableData()

func downloadItems()
{
let url = NSMutableURLRequest(url: NSURL(string:                           "http://www.hholm.dk/time_app/qrcode4.php")! as URL)
    url.httpMethod = "POST"
    let postString = "username=\(code)"
    url.httpBody = postString.data(using: String.Encoding.utf8)
    print(url.httpBody = postString.data(using: String.Encoding.utf8))

    var session: URLSession!
    let configuration = URLSessionConfiguration.default

    session = URLSession(configuration: configuration, delegate: self,  delegateQueue: nil)

    let task = session.dataTask(with: url as URLRequest)

    task.resume()

}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
{
    self.data.append(data as Data);
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
{
    if error != nil
    {
        print("Not Found", error)

    }
    else
    {
        print("Ok")
        self.parseJSON()
    }

}


func parseJSON()
{

    var jsonResult: NSArray = NSArray()

    do
    {
        jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray

        print("jsonResult.count",jsonResult.count)
    }
    catch let error as NSError
    {
        print("jsonResult: ", error)
    }


    var jsonElement: NSDictionary = NSDictionary()
    var contador = 0
    for i in (0..<jsonResult.count)
    {
        jsonElement = jsonResult[i] as! NSDictionary

        if let nameUser = jsonElement["name"] as? String,
            let pointUser = jsonElement["point"] as? String,
            let statusUser = jsonElement["status"] as? String
        {
            getStatusUSer = statusUser
            print("Name: ", nameUser)
            print("Status: ", statusUser)
            print("Point: ", pointUser)

        }

    }
}

}

如何打印值

1 个答案:

答案 0 :(得分:0)

您可以使用协议返回这些值:

import Foundation
import UIKit
var code = "100"
var getStatusUSer = ""

//define the protocol
protocol GetJSONDelegate {
      func didReceiveValues(name: String, status: String, point: String)
}
//I've changed the first char of the class name to uppercase 
class GetJSON: NSObject, URLSessionDataDelegate{
//properties
var data : NSMutableData = NSMutableData()

//delegate
var delegate: GetJSONDelegate?

func downloadItems(){
let url = NSMutableURLRequest(url: NSURL(string:                           "http://www.hholm.dk/time_app/qrcode4.php")! as URL)
    url.httpMethod = "POST"
    let postString = "username=\(code)"
    url.httpBody = postString.data(using: String.Encoding.utf8)
    print(url.httpBody = postString.data(using: String.Encoding.utf8))

    var session: URLSession!
    let configuration = URLSessionConfiguration.default

    session = URLSession(configuration: configuration, delegate: self,  delegateQueue: nil)

    let task = session.dataTask(with: url as URLRequest)

    task.resume()

}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
{
    self.data.append(data as Data);
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
{
    if error != nil
    {
        print("Not Found", error)

    }
    else
    {
        print("Ok")
        self.parseJSON()
    }

}


func parseJSON()
{

    var jsonResult: NSArray = NSArray()

    do
    {
        jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray

        print("jsonResult.count",jsonResult.count)
    }
    catch let error as NSError
    {
        print("jsonResult: ", error)
    }


    var jsonElement: NSDictionary = NSDictionary()
    var contador = 0
    for i in (0..<jsonResult.count)
    {
        jsonElement = jsonResult[i] as! NSDictionary

        if let nameUser = jsonElement["name"] as? String,
            let pointUser = jsonElement["point"] as? String,
            let statusUser = jsonElement["status"] as? String
        {
            getStatusUSer = statusUser
            print("Name: ", nameUser)
            print("Status: ", statusUser)
            print("Point: ", pointUser)

           //here we will return received data to the delegate
          self.delegate?.didReceiveValues(name: nameUser, status: statusUser, point: pointUser)
        }

    }
}

}

现在我们需要将您的控制器设置为该协议的委托:

//this is an example, you need to add the methods described in your controller where you want to use those values

class YourViewController: UIViewController{
     // the method that is called by you to get values
     func downloadItems(){
          let getJson = GetJSON()
          //setting the delegate
          getJson.delegate = self
          //starting download
          getJson.downloadItems()
     }
}

//defining protocol methods in the extension of the view controller
extension YourViewController: GetJSONDelegate {
     func didReceiveValues(name: String, status: String, point: String){
          //now you can use values in your view controller
     }
}