无法从另一个视图控制器Swift获取数组

时间:2014-11-26 14:57:59

标签: ios arrays swift uiviewcontroller

我正在制定一个方向(不知道它是否是正确的英文名称)app。您可以扫描Qr代码,然后将结果发送给您的老师。我使用Multipeer连接从学生电话和老师发送结果。我有一个UITableViewController,我想为另一个视图控制器创建一个数组(带有一个struct,2个值) - > UIViewController中。而且存在问题。当我尝试"发送"它到另一个viewControler它没有达到最终的东西。我已经尝试了所有的东西(controlsGetShared是一次尝试)我可以,但它仍然无法工作...... :(

Struct看起来像这样

struct Control {
let name: String
let code: String 
}

UITableViewController看起来像

import UIKit

class ControlViewController: UITableViewController {

var controlsGet = [Control] ()
var controlsGetShare = [Control] ()

var def = NSUserDefaults.standardUserDefaults()

var valueName: String = ""
var valueCode: String = ""

@IBAction func done(segue: UIStoryboardSegue) {
    var scanVc = segue.sourceViewController as ScanViewController
    valueName = scanVc.name
    valueCode = scanVc.code

    println("sendToSendFile \(valueName)  \(valueCode)")

    controlsGet.append(Control(name: valueName, code: valueCode))
    //controlsGetShare.append(Control(name: valueName, code: valueCode))
    println("\(self.controlsGet.count) shareArray \(self.controlsGetShare.count)")
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    controlsGetShare = controlsGet
    println("preparaForSegueCount \(controlsGetShare.count)")
}

override func viewDidLoad() {
    println("viewDidLoad")
    tableView.reloadData()

    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.controlsGet.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    //for index in controlsGet {

    var control : Control

    control = controlsGet[indexPath.row]

    cell.textLabel.text = control.name
    cell.detailTextLabel?.text = control.code
    //}
    return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        controlsGet.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
}

Ant发送UIViewControler

import UIKit
import MultipeerConnectivity

class SendFileViewController: UIViewController, MCBrowserViewControllerDelegate,
MCSessionDelegate {

let serviceType = "LCOC-Chat"

var controlsGetShare = [Control] ()

@IBAction func done(segue: UIStoryboardSegue) {
    var controlVc = segue.sourceViewController as ControlViewController

    println(controlVc.controlsGetShare.count)

    controlsGetShare = controlVc.controlsGetShare
    println(controlsGetShare.count)
}

var browser : MCBrowserViewController!
var assistant : MCAdvertiserAssistant!
var session : MCSession!
var peerID: MCPeerID!

@IBOutlet var chatView: UITextView!
@IBOutlet var messageField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    self.peerID = MCPeerID(displayName: UIDevice.currentDevice().name)
    self.session = MCSession(peer: peerID)
    self.session.delegate = self

    // create the browser viewcontroller with a unique service name
    self.browser = MCBrowserViewController(serviceType:serviceType,
        session:self.session)

    self.browser.delegate = self;

    self.assistant = MCAdvertiserAssistant(serviceType:serviceType,
        discoveryInfo:nil, session:self.session)

    // tell the assistant to start advertising our fabulous chat
    self.assistant.start()
}

@IBAction func sendChat(sender: UIButton) {
    println("sendButton")
    // Bundle up the text in the message field, and send it off to all
    // connected peers
    var error : NSError?
    var message = ""

    /*
    var msg = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
    self.session.sendData(msg, toPeers: self.session.connectedPeers, withMode: MCSessionSendDataMode.Unreliable, error: &error)

    */
    println(self.controlsGetShare.count)/*
    for index in controlsGetShare {

        message = index.name
        var msg = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        self.session.sendData(msg, toPeers: self.session.connectedPeers, withMode: MCSessionSendDataMode.Unreliable, error: &error)

        if error != nil {
            print("Error sending nameData: \(error?.localizedDescription)")
        }
        println("didSendDataA")

        message = index.code
        msg = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        self.session.sendData(msg, toPeers: self.session.connectedPeers, withMode: MCSessionSendDataMode.Unreliable, error: &error)

        if error != nil {
            print("Error sending codeData: \(error?.localizedDescription)")
        }
        println("didSendDataB")
    }*/
}

@IBAction func showBrowser(sender: UIButton) {
    // Show the browser view controller
    self.presentViewController(self.browser, animated: true, completion: nil)
}

func browserViewControllerDidFinish(
    browserViewController: MCBrowserViewController!)  {
        // Called when the browser view controller is dismissed (ie the Done
        // button was tapped)

        self.dismissViewControllerAnimated(true, completion: nil)
}

func browserViewControllerWasCancelled(
    browserViewController: MCBrowserViewController!)  {
        // Called when the browser view controller is cancelled

        self.dismissViewControllerAnimated(true, completion: nil)
}

func session(session: MCSession!, didReceiveData data: NSData!,
    fromPeer peerID: MCPeerID!)  {
        // Called when a peer sends an NSData to us

        // This needs to run on the main queue
        dispatch_async(dispatch_get_main_queue()) {

            var msg = NSString(data: data, encoding: NSUTF8StringEncoding)

            //self.updateChat(msg, fromPeer: peerID)
        }
}

// The following methods do nothing, but the MCSessionDelegate protocol
// requires that we implement them.
func session(session: MCSession!,
    didStartReceivingResourceWithName resourceName: String!,
    fromPeer peerID: MCPeerID!, withProgress progress: NSProgress!)  {

        // Called when a peer starts sending a file to us
}

func session(session: MCSession!,
    didFinishReceivingResourceWithName resourceName: String!,
    fromPeer peerID: MCPeerID!,
    atURL localURL: NSURL!, withError error: NSError!)  {
        // Called when a file has finished transferring from another peer
}

func session(session: MCSession!, didReceiveStream stream: NSInputStream!,
    withName streamName: String!, fromPeer peerID: MCPeerID!)  {
        // Called when a peer establishes a stream with us
}

func session(session: MCSession!, peer peerID: MCPeerID!,
    didChangeState state: MCSessionState)  {
        // Called when a connected peer changes state (for example, goes offline)

}

}

大部分代码都来自我在互联网上找到的源代码,所以这就是所有评论的原因。谢谢 //安东

0 个答案:

没有答案