質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Swift 2

Swift 2は、Apple社が独自に開発を行っている言語「Swift」のアップグレード版です。iOSやOS X、さらにLinuxにも対応可能です。また、throws-catchベースのエラーハンドリングが追加されています。

Q&A

解決済

1回答

2306閲覧

multipeerconectivityを用いて接続を行った後、遷移先の画面で、データのやり取りがしたい

afuroda

総合スコア36

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Swift 2

Swift 2は、Apple社が独自に開発を行っている言語「Swift」のアップグレード版です。iOSやOS X、さらにLinuxにも対応可能です。また、throws-catchベースのエラーハンドリングが追加されています。

0グッド

0クリップ

投稿2016/11/12 06:49

編集2016/11/13 15:59

###前提・実現したいこと
multipeerconectivityを用いて2端末間でデータを送受信したいのですが、2端末の接続が成功したところで画面を遷移して、もう一つの画面でデータのやり取りをしたいのですが、その方法がよくわからなくて困っています。

###発生している問題

データの受信を始めの画面で行ってしまう

###該当のソースコード

swift

1import UIKit 2import MultipeerConnectivity 3class ViewController: UIViewController,MCSessionDelegate,MCNearbyServiceBrowserDelegate,MCNearbyServiceAdvertiserDelegate { 4 5 let peer : MCPeerID = MCPeerID(displayName: UIDevice.currentDevice().name) 6 7 var browser : MCNearbyServiceBrowser? 8 var advertis : MCNearbyServiceAdvertiser? 9 let service = "p2p" 10 var appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate 11 12 override func viewDidLoad() { 13 appdelegate.session = MCSession(peer: peer) 14 appdelegate.session!.delegate = self 15 self.browser = MCNearbyServiceBrowser(peer: peer, serviceType: service) 16 self.browser!.delegate = self 17 self.advertis = MCNearbyServiceAdvertiser(peer: peer, discoveryInfo: nil, serviceType: service) 18 self.advertis?.delegate = self 19 super.viewDidLoad() 20 // Do any additional setup after loading the view, typically from a nib. 21 } 22 23 override func didReceiveMemoryWarning() { 24 super.didReceiveMemoryWarning() 25 // Dispose of any resources that can be recreated. 26 } 27 28 @IBAction func browser(sender: AnyObject) { 29 30 self.browser!.startBrowsingForPeers() 31 } 32 33 @IBAction func advertiser(sender: AnyObject) { 34 self.advertis!.startAdvertisingPeer() 35 } 36 func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) { 37 print("[MCNearbyServiceBrowserDelegate] browser:foundPeer:withDiscoveryInfo:") 38 print(" + peerID = \(peerID.displayName)") 39 print(" + info = \(info)") 40 browser.invitePeer(peerID, toSession: appdelegate.session!, withContext: nil, timeout: 10) 41 } 42 43 func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) { 44 print("[MCNearbyServiceBrowserDelegate] browser:lostPeer:") 45 print(" + peerID = \(peerID.displayName)") 46 } 47 48 49 // MARK:- MCNearbyServiceAdvertiserDelegate 50 51 func advertiser(advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: NSData?, invitationHandler: (Bool, MCSession) -> Void) { 52 print("[MCNearbyServiceAdvertiserDelegate] advertiser:didReceiveInvitationFromPeer:withContext:invitationHandler:") 53 print(" + peerID = \(peerID.displayName)") 54 55 let alert = UIAlertController(title: "招待を受けました", message: "from \(peerID.displayName)", preferredStyle: .Alert) 56 alert.addAction(UIAlertAction(title: "参加", style: .Default) { action in 57 invitationHandler(true, self.appdelegate.session!) 58 }) 59 alert.addAction(UIAlertAction(title: "拒否", style: .Cancel) { action in 60 invitationHandler(false, self.appdelegate.session!) 61 }) 62 self.presentViewController(alert, animated: true, completion: nil) 63 } 64 func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) { 65 //画面遷移のコード 66 let viewcontroller = self.storyboard!.instantiateViewControllerWithIdentifier("view2") 67 self.presentViewController(viewcontroller,animated: true,completion: nil) 68 print("change window") 69 70 } 71 func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) { 72 print("receivedData") 73 } 74 75 func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID) { 76 } 77 78 func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) { 79 } 80 81 func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) { 82 } 83 84} 85
import UIKit import MultipeerConnectivity class secondViewController: UIViewController { let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //view1に戻る @IBAction func Modori(sender: AnyObject) { let viewcontroller = self.storyboard!.instantiateViewControllerWithIdentifier("view1") self.presentViewController(viewcontroller,animated: true, completion: nil) } @IBAction func send(sender: AnyObject) { let str = "text" let data = (str as NSString).dataUsingEncoding(NSUTF8StringEncoding) do{ try appdelegate.session?.sendData(data!, toPeers: (appdelegate.session?.connectedPeers)!, withMode: .Reliable) }catch let error as NSError{ print("sned error") } } func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) { print("received Data") } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
import UIKit import MultipeerConnectivity @UIApplicationMain class AppDelegate: UIResponder,UIApplicationDelegate { var window: UIWindow? var session : MCSession? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }

###試したこと
secondViewController.swiftにDidReciveDataを書いて試してみましたが、初めの画面で、受信しています。

###補足情報(言語/FW/ツール等のバージョンなど)
プログラムは、上から、viewcontroller.swift secondViewController.swift appdelegate.swiftです。
宜しくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

切り替えたいタイミングで、MCSession()のdelegateにsecondViewControllerのインスタンスをセットしてやればいいと思います。

投稿2016/11/14 07:12

fuzzball

総合スコア16731

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

afuroda

2016/11/14 10:41

切り替えたいタイミングとはfunc session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) { //画面遷移のコード let viewcontroller = self.storyboard!.instantiateViewControllerWithIdentifier("view2") self.presentViewController(viewcontroller,animated: true,completion: nil) print("change window") の画面を切り替えたい所のことですか?
fuzzball

2016/11/14 11:00

そこか、secondViewControllerのviewDidLoadあたりでいいんじゃないかと。 ご自身で検証してみて下さい。
afuroda

2016/11/16 15:46

secondViewControllerのviewDidLoadにappdelegate.session?.delegate = selfとかいたらうまく動くました。ありがとうございます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問