Xml parser function never gets called - ios

I'm currently working with swift and trying to make and RSS reader iOS iPhone app. I'm currently having trouble with calling the parser function. I'm really trying to replicate what I developed in Objective-C (which works well) with Swift.
This is my tableView.swift class
import UIKit
class FeedTableViewController: UITableViewController, NSXMLParserDelegate {
var parser: NSXMLParser = NSXMLParser()
var feeds: NSMutableArray = []
var fItem = Dictionary<String, Float>()
var fTitle: String = String()
var element: String = String()
override func viewDidLoad() {
super.viewDidLoad()
var url: NSURL = NSURL.URLWithString("http://feeds.feedburner.com/TouchCodeMagazine")
parser = NSXMLParser(contentsOfURL: url)
parser.delegate = self
parser.shouldResolveExternalEntities = false
parser.parse()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return feeds.count
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let CellId: NSString = "Cell"
var cell: UITableViewCell = tableView?.dequeueReusableCellWithIdentifier(CellId) as UITableViewCell
if let ip = indexPath {
cell.textLabel.text = "hello\(ip.row)"
}
return cell
}
// This function is never called.
func parser(parser: NSXMLParser!, didStartElement elementName: String!, nameSpaceURI namespaceURI: String!, qualifiedName: String!, attributes attributeDict: Dictionary<String, Float>) {
element = elementName
println(element) // This line is never executed.
}
}
I have set the NSXMLParserDelegate but still it never gets called.
Any idea on what I can do to get this working? This is all the code I have so far. Maybe I need to import e certain framework?

Try:
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName: String!, attributes: Dictionary<String, Float>) {
println(elementName) // This line is never executed.
}
Correction: Actually, it's not the last parameter, it's the spelling of namespaceURI vs. nameSpaceURI in your original.
Copied and pasted again out of working playground.

Related

How to print data in empty array

I'm trying to print the chat array that is declared as a empty global variable in a table. The data that I'm trying to print is received using web sockets. I'm assigning the data in the messageReceived function, and I know that the data is getting to the program because I'm printing in a label, but the moment that I'm trying to print it in the table is simple not working. All of this is in the ViewController.swift:
import UIKit
import Starscream
var messagetext: String = ""
var tabletext: String = ""
var chat = [String] ()
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
var socket = WebSocket(url: URL(string: "ws://localhost:1337/")!, protocols: ["chat"])
#IBOutlet weak var chatMessage: UILabel!
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var tableView: UITableView!
#IBAction func buttonClick(_ sender: Any) {
messagetext = textField.text!
sendMessage(messagetext)
}
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
socket.delegate = self
socket.connect()
navigationItem.hidesBackButton = true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldDidEndEditing(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return (true)
}
deinit{
socket.disconnect(forceTimeout: 0)
socket.delegate = nil
}
}
// MARK: - FilePrivate
fileprivate extension ViewController {
func sendMessage(_ messager: String) {
socket.write(string: messager)
}
func messageReceived(_ message: String) {
chatMessage.text = message
chat.append(message)
}
}
// MARK: - WebSocketDelegate
extension ViewController : WebSocketDelegate {
public func websocketDidConnect(_ socket: Starscream.WebSocket) {
}
public func websocketDidDisconnect(_ socket: Starscream.WebSocket, error: NSError?) {
performSegue(withIdentifier: "websocketDisconnected", sender: self)
}
public func websocketDidReceiveMessage(_ socket: Starscream.WebSocket, text: String) {
// 1
guard let data = text.data(using: .utf16),
let jsonData = try? JSONSerialization.jsonObject(with: data),
let jsonDict = jsonData as? [String: Any],
let messageType = jsonDict["type"] as? String else {
return
}
// 2
if messageType == "message",
let messageData = jsonDict["data"] as? [String: Any],
let messageText = messageData["text"] as? String {
messageReceived(messageText)
}
}
public func websocketDidReceiveData(_ socket: Starscream.WebSocket, data: Data) {
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return(chat.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = chat[indexPath.row] as! String
return(cell)
}
}
Assuming that you are sure about there is data to be received by your view controller, The issue would be: the tableview data source methods are called before receiving any data, which means chat data source array is still empty, thus there is no data to display.
The solution for your case is to make sure to reload the tableview after receiving data (updating the value of chat data source array), which means in your case after appending a message to chat in messageReceived method by calling reloadData() UITableView instance method:
func messageReceived(_ message: String) {
chatMessage.text = message
chat.append(message)
// here we go:
tableView.reloadData()
}
In your message received handler, issue a tableview.reloadData()
Cheers!
You need to tell the tableview that there is new data. You also need to allow for the fact that the network operation probably occurred on a background queue and UI updates must be on the main queue:
func messageReceived(_ message: String) {
DispatchQueue.main.async {
let newRow = IndexPath(row: chat.count, section:0)
chatMessage.text = message
chat.append(message)
tableView.insertRows(at:[newRow],with: .automatic)
}
}

Swift Firebase persistence

I'm trying to enable Firebase Persistence but my code keeps crashing with:
terminating with uncaught exception of type NSException
I have tried the line of code under my viewDidLoad as well as under DataService but I still get the same crash. what do I need to do to resolve this problem I'm facing
import UIKit
import Firebase
class HomeTeamSelectionVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var club: Clubs!
var player = [Players]()
var playerFirstName = String()
var playerLastName = String()
var playerSelected: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
FIRDatabase.database().persistenceEnabled = true //Correct use of????
CLUB_KEY = ""
CLUB_KEY = club.clubKey
tableView.dataSource = self
tableView.delegate = self
DataService.ds.REF_PLAYERS.queryOrdered(byChild: "clubKey").queryEqual(toValue: club.clubKey).observe(.value, with: { (snapshot) in
print("PLAYERS_COUNT: \(snapshot.childrenCount)")
print("PLAYERS_SNAPSHOT: \(snapshot)")
self.player = []
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
if let playerDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let players = Players(playerKey: key, dictionary: playerDict)
self.player.append(players)
}
}
}
// self.tableView.reloadData()
}) { (error) in
print(error.localizedDescription)
print("CHET: local error")
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return player.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let players = player[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTeamPlayersCell") as? HomeTeamPlayersCell {
cell.configureCell(players)
return cell
} else {
return HomeTeamPlayersCell()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let players: Players!
players = player[indexPath.row]
print (players.playerKey)
print (players.playerFirstName)
print (players.playerLastName)
dismiss(animated: true, completion: nil)
}
}
From Firebase documentation for persistenceEnabled property:
Note that this property must be set before creating your first Database reference and only needs to be called once per application.
As such, the standard practice is to set it once in your AppDelegate class. For instance:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FIRApp.configure()
FIRDatabase.database().persistenceEnabled = true
...
return true
}

Refresh function does not work as expected Swift 3

So, I have this app which loads rss feeds and I have implemented refresh function. Upload refreshing, it does reloads and adds the new post if it's posted but the previous data stays there and gets added on to the stack. Check the code and images. I am attaching below.
//
// TableViewController.swift
// WebView
//
import UIKit
class TableViewController: UITableViewController,XMLParserDelegate{
var currentElement:String = ""
var postTitle:String = ""
var webLink:String = ""
var feeds:[Model] = []
var reload: UIRefreshControl! = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
//let urlToSend: NSURL = NSURL(string: "https://sensodyneforsensitiveteeth.wordpress.com/feed")!
let urlToSend: NSURL = NSURL(string: "http://froshgeek.com/feed")!
let parser = XMLParser(contentsOf: urlToSend as URL)!
parser.delegate = self
parser.parse()
//reload
reload!.attributedTitle = NSAttributedString(string: "Pull to reload the page")
reload!.addTarget(self, action: #selector(TableViewController.reloadFunc), for: UIControlEvents.valueChanged)
tableView.addSubview(reload)
reload.endRefreshing()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
currentElement=elementName;
if(elementName=="item")
{
postTitle = String()
webLink = String()
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if(elementName=="item"){
let feed: Model = Model()
feed.postTitle = postTitle
feed.webLink = webLink
feeds.append(feed)
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
let data = string.replacingOccurrences(of: "^\\s*", with: "", options: .regularExpression)
if (!data.isEmpty){
if currentElement == "title" {
postTitle += data
}
else if currentElement == "link" {
webLink += data
}
}
}
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
print("Bad XML File, Please validate")
}
func reloadFunc(_ sender: AnyObject){
viewDidLoad()
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return feeds.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "webFeeds", for: indexPath)
let feeds: Model = self.feeds[indexPath.row]
cell.textLabel?.text = feeds.postTitle
return cell
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "webParse" {
let feed: Model = feeds[tableView.indexPathForSelectedRow!.row]
let pageView = segue.destination as! ViewController
pageView.webLink = feed.webLink
}
}
func parserDidEndDocument(_ parser: XMLParser){
self.tableView.reloadData();
self.refreshControl?.endRefreshing();
}
}
Model.swift
//
// Model.swift
// WebView
//
import Foundation
class Model {
var postTitle:String = ""
var webLink:String = ""
var currentElement:String = ""
}
ViewController.swift
//
// ViewController.swift
// WebView
//
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var showPage: UIWebView!
var webLink: String = String()
override func viewDidLoad() {
super.viewDidLoad()
let link : NSURL = NSURL(string: webLink)!
let req : NSURLRequest = NSURLRequest(url: link as URL)
showPage.loadRequest (req as URLRequest)
showPage.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Screenshot upon reloading
The reason it is adding object at last is because you need to empty your array before refreshing data. Also never call viewDidLoad explicitly what you need to do is make one method that make this API request and call that method from viewDidLoad and your refresh method.
override func viewDidLoad() {
super.viewDidLoad()
//call function to get xml data
self.getData()
//reload
reload!.attributedTitle = NSAttributedString(string: "Pull to reload the page")
reload!.addTarget(self, action: #selector(TableViewController.reloadFunc), for: UIControlEvents.valueChanged)
tableView.addSubview(reload)
reload.endRefreshing()
}
func getData() {
//Make array empty first
feeds = []
let urlToSend: NSURL = NSURL(string: "http://froshgeek.com/feed")!
let parser = XMLParser(contentsOf: urlToSend as URL)!
parser.delegate = self
parser.parse()
}
Now call this getData function in your refresh action method reloadFunc
func reloadFunc(_ sender: AnyObject){
self.getData()
self.tableView.reloadData()
}

Filter result from parse query

Hi Im developing a chat app with parse and I have one group-chat tab. What I would like to accomplish Is that when the user registers he/she can choose from a list of "tags" for example, "cats", "dogs" and "cars". Then when the user is signed in the groups tab only shows group-chats associated to the chosen tags. Right now i have a function where the user can create a group-chat but If possible i want to remove that and use my idea that I explained above.
Here's my code for the group's tab:
import UIKit
// Parse loaded from SwiftParseChat-Bridging-Header.h
class GroupsViewController: UITableViewController, UIAlertViewDelegate {
var groups: [PFObject]! = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if PFUser.currentUser() != nil {
self.loadGroups()
}
else {
Utilities.loginUser(self)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadGroups() {
var query = PFQuery(className: PF_GROUPS_CLASS_NAME)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) in
if error == nil {
self.groups.removeAll()
self.groups.extend(objects as [PFObject]!)
self.tableView.reloadData()
} else {
ProgressHUD.showError("Network error")
println(error)
}
}
}
#IBAction func newButtonPressed(sender: UIBarButtonItem) {
self.actionNew()
}
func actionNew() {
var alert = UIAlertView(title: "Please enter a name for your group", message: "", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
alert.alertViewStyle = UIAlertViewStyle.PlainTextInput
alert.show()
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex != alertView.cancelButtonIndex {
var textField = alertView.textFieldAtIndex(0);
if let text = textField!.text {
if countElements(text) > 0 {
var object = PFObject(className: PF_GROUPS_CLASS_NAME)
object[PF_GROUPS_NAME] = text
object.saveInBackgroundWithBlock({ (success: Bool, error: NSError!) -> Void in
if success {
self.loadGroups()
} else {
ProgressHUD.showError("Network error")
println(error)
}
})
}
}
}
}
// MARK: - TableView Data Source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.groups.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
var group = self.groups[indexPath.row]
cell.textLabel?.text = group[PF_GROUPS_NAME] as? String
var query = PFQuery(className: PF_CHAT_CLASS_NAME)
query.whereKey(PF_CHAT_GROUPID, equalTo: group.objectId)
query.orderByDescending(PF_CHAT_CREATEDAT)
query.limit = 1000
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if let chat = objects.first as? PFObject {
let date = NSDate()
let seconds = date.timeIntervalSinceDate(chat.createdAt)
let elapsed = Utilities.timeElapsed(seconds);
let countString = (objects.count > 1) ? "\(objects.count) meddelanden" : "\(objects.count) meddelande"
cell.detailTextLabel?.text = "\(countString) \(elapsed)"
} else {
cell.detailTextLabel?.text = "0 meddelanden"
}
cell.detailTextLabel?.textColor = UIColor.lightGrayColor()
}
return cell
}
// MARK: - TableView Delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var group = self.groups[indexPath.row]
let groupId = group.objectId as String
Messages.createMessageItem(PFUser(), groupId: groupId, description: group[PF_GROUPS_NAME] as String)
self.performSegueWithIdentifier("groupChatSegue", sender: groupId)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "groupChatSegue" {
let chatVC = segue.destinationViewController as ChatViewController
chatVC.hidesBottomBarWhenPushed = true
let groupId = sender as String
chatVC.groupId = groupId
}
}
}
It sounds like you want to query a class (the one containing chats) with the constraint that an array column property of that class (the one listing each chat's tags) contains some list of tags related to the current user. PFQuery has a method called whereKey:containsAllObjectsInArray: which does exactly that.
To make it work, you need to be clear about whether the list of tags is an array of pointers to tag objects, or an array of strings that are tag names. Naturally, if tags on chats are stored as pointers to objects, then the second parameter should be an array of PFObject, and if they are strings, then the array parameter must be an array of NSString.
Unrelated to the semantics of the query, but important: Doing an unguarded, asynch query for anything in cellForRowAtIndexPath: will be unproductive. This method is called every time a cell scrolls into view, which happens arbitrarily often, and arbitrarily rapidly. Use another method to fetch the table's datasource, then reload the table once the data arrives.
(I think the post has been given a close vote because it asks a specific question, then presents the reader with a lot of code, much of it unrelated, leaving the reader to find the relevant query, and showing no indication of what's been tried so far. The site will work better for you if you give maximum help to those who might answer an otherwise good question).

Can't get an array from another view controller Swift

I'm making an Orientation (don't know if it's the right name in english) app. You can scan a Qr code and then you can send the results to your teacher. I'm using Multipeer connection to send the results from the students phone and the teachers. I have one UITableViewController and I want to make an array (with a struct, 2 values) available for another view controller -> UIViewController. And there's the problem. When I try to "send" it to the other viewControler it doesn't reach to the end ore something. I have tried everything (controlsGetShared is one try) I can, but still it doesn't work... :(
The Struct looks like this
struct Control {
let name: String
let code: String
}
The UITableViewController looks like
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 the send 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)
}
}
Much of the code are from source codes I found on the internet, so that's why all the comments.Thanks
//Anton

Resources