From c373618b17684bb9ca0fdacf597ffc15cc8432ec Mon Sep 17 00:00:00 2001 From: Emily Marigold Klassen Date: Mon, 18 Sep 2017 11:06:25 -0700 Subject: [PATCH 1/2] Upgrade to swift 3 --- .../AppIcon.appiconset/Contents.json | 20 ++ MeatChat/MCAppDelegate.swift | 12 +- MeatChat/MCPost.swift | 38 ++-- MeatChat/MCPostCell.swift | 10 +- MeatChat/MCPostListViewController.swift | 204 +++++++++--------- MeatChat/MCPostViewController.swift | 166 +++++++------- MeatChat/MeatChat2-Info.plist | 2 + MeatChat/UIImage-Scaled.swift | 14 +- MeatChat2.xcodeproj/project.pbxproj | 71 +++--- Podfile.lock | 4 +- 10 files changed, 290 insertions(+), 251 deletions(-) diff --git a/MeatChat/Images.xcassets/AppIcon.appiconset/Contents.json b/MeatChat/Images.xcassets/AppIcon.appiconset/Contents.json index d3e9f62..d7772f4 100644 --- a/MeatChat/Images.xcassets/AppIcon.appiconset/Contents.json +++ b/MeatChat/Images.xcassets/AppIcon.appiconset/Contents.json @@ -1,5 +1,15 @@ { "images" : [ + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, { "size" : "29x29", "idiom" : "iphone", @@ -34,6 +44,16 @@ "filename" : "appicon-60@3x.png", "scale" : "3x" }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "2x" + }, { "size" : "29x29", "idiom" : "ipad", diff --git a/MeatChat/MCAppDelegate.swift b/MeatChat/MCAppDelegate.swift index 764eff5..6568c81 100644 --- a/MeatChat/MCAppDelegate.swift +++ b/MeatChat/MCAppDelegate.swift @@ -13,7 +13,7 @@ class MCAppDelegate : UIResponder, UIApplicationDelegate { var window:UIWindow? - func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) @@ -21,13 +21,13 @@ class MCAppDelegate : UIResponder, UIApplicationDelegate { print(error) } - let defaultDefaults = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("DefaultDefaults", ofType: "plist")!) as? Dictionary - NSUserDefaults.standardUserDefaults().registerDefaults(defaultDefaults!) + let defaultDefaults = NSDictionary(contentsOfFile: Bundle.main.path(forResource: "DefaultDefaults", ofType: "plist")!) as? Dictionary + UserDefaults.standard.register(defaults: defaultDefaults!) return true } - func applicationDidEnterBackground(application: UIApplication) { + func applicationDidEnterBackground(_ application: UIApplication) { if let nc=self.window?.rootViewController as? UINavigationController { if let vc=nc.topViewController as? MCPostListViewController { vc.postViewController?.closePostWithPosted(false) @@ -35,7 +35,7 @@ class MCAppDelegate : UIResponder, UIApplicationDelegate { } } - func applicationWillEnterForeground(application: UIApplication) { + func applicationWillEnterForeground(_ application: UIApplication) { if let nc=self.window?.rootViewController as? UINavigationController { if let vc=nc.topViewController as? MCPostListViewController { vc.resumePlay() @@ -43,7 +43,7 @@ class MCAppDelegate : UIResponder, UIApplicationDelegate { } } - func applicationWillTerminate(application: UIApplication) { + func applicationWillTerminate(_ application: UIApplication) { if let nc=self.window?.rootViewController as? UINavigationController { if let vc=nc.topViewController as? MCPostListViewController { vc.flushItems() diff --git a/MeatChat/MCPost.swift b/MeatChat/MCPost.swift index c287f54..2f8ac89 100644 --- a/MeatChat/MCPost.swift +++ b/MeatChat/MCPost.swift @@ -13,53 +13,53 @@ class MCPost :NSObject { var postData: [String : AnyObject] var attributedString : NSAttributedString; - var videoUrl : NSURL; + var videoUrl : URL; var created :Int; var fingerprint :String; init(dict: NSDictionary ) { - self.postData = dict.dictionaryWithValuesForKeys(["message","created"]) + self.postData = dict.dictionaryWithValues(forKeys: ["message","created"]) as [String : AnyObject] self.created = (dict["created"] as? Int)! self.fingerprint = (dict["fingerprint"] as? String)! self.attributedString=NSAttributedString() - let media: String = (dict["media"]!.substringFromIndex(22) as String) - self.videoUrl=NSURL() + let media: String = ((dict["media"]! as AnyObject).substring(from: 22) as String) + self.videoUrl=URL(string: "")! super.init() self.setAttributedBody() - let videoData: NSData = NSData(base64EncodedString: media, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)! - videoData.writeToURL(self.path()!, atomically: false) + let videoData: Data = Data(base64Encoded: media, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)! + try? videoData.write(to: self.path()!, options: []) self.videoUrl = self.path()! do { - try self.videoUrl.setResourceValue(true, forKey: NSURLIsExcludedFromBackupKey) + try (self.videoUrl as NSURL).setResourceValue(true, forKey: URLResourceKey.isExcludedFromBackupKey) } catch { print(error) } return } - func path() -> NSURL? { + func path() -> URL? { - let fileManager = NSFileManager.defaultManager() + let fileManager = FileManager.default - let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) + let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask) - let documentDirectory: NSURL = urls.first! - let finalPath = documentDirectory.URLByAppendingPathComponent(String(self.created)+".mp4") + let documentDirectory: URL = urls.first! + let finalPath = documentDirectory.appendingPathComponent(String(self.created)+".mp4") return finalPath } func relativeTime() -> String { - let epoch: NSTimeInterval = Double(created)/1000 - let postDate: NSDate = NSDate(timeIntervalSince1970: epoch) - return postDate.dateTimeAgo() + let epoch: TimeInterval = Double(created)/1000 + let postDate: Date = Date(timeIntervalSince1970: epoch) + return (postDate as NSDate).dateTimeAgo() } func cleanup() { do { - try NSFileManager.defaultManager().removeItemAtURL(self.path()!) + try FileManager.default.removeItem(at: self.path()!) } catch { print(error) } @@ -79,10 +79,10 @@ class MCPost :NSObject { do { - let string:NSMutableAttributedString = try NSMutableAttributedString(data: html.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding ], documentAttributes: nil) - string.addAttribute(NSBackgroundColorAttributeName, value: UIColor.whiteColor(), range: NSMakeRange(0,string.length)) + let string:NSMutableAttributedString = try NSMutableAttributedString(data: html.data(using: String.Encoding.utf8)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 ], documentAttributes: nil) + string.addAttribute(NSBackgroundColorAttributeName, value: UIColor.white, range: NSMakeRange(0,string.length)) string.addAttribute(NSForegroundColorAttributeName, value: UIColor(white: 0.23, alpha: 1.0), range: NSMakeRange(0,string.length)) - string.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(17), range: NSMakeRange(0,string.length)) + string.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 17), range: NSMakeRange(0,string.length)) string.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0,string.length)) self.attributedString=string diff --git a/MeatChat/MCPostCell.swift b/MeatChat/MCPostCell.swift index c431007..e1b62ac 100644 --- a/MeatChat/MCPostCell.swift +++ b/MeatChat/MCPostCell.swift @@ -23,16 +23,16 @@ class MCPostCell : UITableViewCell { override func awakeFromNib() { self.videoPlayer=AVPlayer(); let layer:AVPlayerLayer=AVPlayerLayer(player: self.videoPlayer) - self.videoPlayer!.actionAtItemEnd=AVPlayerActionAtItemEnd.None - layer.frame=CGRectMake(0, 0, 100, 75); + self.videoPlayer!.actionAtItemEnd=AVPlayerActionAtItemEnd.none + layer.frame=CGRect(x: 0, y: 0, width: 100, height: 75); layer.videoGravity=AVLayerVideoGravityResizeAspectFill; self.video?.layer.addSublayer(layer) } - func playerItemDidReachEnd(notification:NSNotification) + func playerItemDidReachEnd(_ notification:Notification) { let p:AVPlayerItem = notification.object as! AVPlayerItem - p.seekToTime(kCMTimeZero) + p.seek(to: kCMTimeZero) } -} \ No newline at end of file +} diff --git a/MeatChat/MCPostListViewController.swift b/MeatChat/MCPostListViewController.swift index 4466fba..b64c23a 100644 --- a/MeatChat/MCPostListViewController.swift +++ b/MeatChat/MCPostListViewController.swift @@ -31,25 +31,25 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl var acceptedEula:Bool! override func viewDidLoad() { - if let blockList=NSUserDefaults.standardUserDefaults().dictionaryForKey("meatspaceBlocks") { - blocked=blockList + if let blockList=UserDefaults.standard.dictionary(forKey: "meatspaceBlocks") { + blocked=blockList as [String : AnyObject] } if((blocked.count) > 0) { - blockButton.hidden=false + blockButton.isHidden=false } - acceptedEula=NSUserDefaults.standardUserDefaults().boolForKey("acceptedEula"); + acceptedEula=UserDefaults.standard.bool(forKey: "acceptedEula"); if(!self.acceptedEula) { - let eulaAlert = UIAlertController(title: "Welcome to MeatChat", message: "This is a client for the real time chat service chat.meatspac.es. Please behave nicely, objectionable content is not accepted. If someone else posts objectionable content, you can remove current and future messages from them, by using the 'block' button next to their message.", preferredStyle: UIAlertControllerStyle.Alert) - let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (UIAlertAction) -> Void in + let eulaAlert = UIAlertController(title: "Welcome to MeatChat", message: "This is a client for the real time chat service chat.meatspac.es. Please behave nicely, objectionable content is not accepted. If someone else posts objectionable content, you can remove current and future messages from them, by using the 'block' button next to their message.", preferredStyle: UIAlertControllerStyle.alert) + let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { (UIAlertAction) -> Void in exit(0); }) eulaAlert.addAction(cancelAction) - let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in + let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (UIAlertAction) -> Void in self.acceptedEula=true; - NSUserDefaults.standardUserDefaults().setBool(self.acceptedEula, forKey: "acceptedEula") + UserDefaults.standard.set(self.acceptedEula, forKey: "acceptedEula") }) eulaAlert.addAction(OKAction) - self.presentViewController(eulaAlert, animated: true, completion: nil) + self.present(eulaAlert, animated: true, completion: nil) } tableView.contentInset = UIEdgeInsetsMake(42, 0, 0, 0); @@ -58,8 +58,8 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard)) self.view.addGestureRecognizer(tap) - NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MCPostListViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) - NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MCPostListViewController.keyboardDidShow(_:)), name: UIKeyboardDidShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(MCPostListViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(MCPostListViewController.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) self.tableView.rowHeight = UITableViewAutomaticDimension; self.tableView.estimatedRowHeight=75; @@ -67,11 +67,11 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl } func scrollToBottom() { - let indexPath=NSIndexPath(forItem: (self.items.count-1), inSection: 0) - self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true) + let indexPath=IndexPath(item: (self.items.count-1), section: 0) + self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.bottom, animated: true) } - func scrollViewWillBeginDragging(scrollView: UIScrollView) { + func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { self.atBottom = false; for cell in self.tableView.visibleCells { if let postCell = cell as? MCPostCell { @@ -90,7 +90,7 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl } - func endScroll(scrollView:UIScrollView) { + func endScroll(_ scrollView:UIScrollView) { self.resumePlay(); let height = scrollView.frame.size.height; let contentYoffset = scrollView.contentOffset.y; @@ -99,33 +99,33 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl } - func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { + func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { self.endScroll(scrollView) } - func scrollViewDidEndDecelerating(scrollView: UIScrollView) { + func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.endScroll(scrollView) } - func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { + func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { self.resumePlay() } - override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { - if let ctrl=segue.destinationViewController as? MCPostViewController { + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if let ctrl=segue.destination as? MCPostViewController { self.postViewController=ctrl } } func setupReachability() { - let server_url=NSURL(string: NSUserDefaults.standardUserDefaults().objectForKey("server_url") as! String); + let server_url=URL(string: UserDefaults.standard.object(forKey: "server_url") as! String); let reach = Reachability(hostname: server_url!.host); - NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MCPostListViewController.reachabilityChanged(_:)), name: kReachabilityChangedNotification, object: nil) - reach.startNotifier() + NotificationCenter.default.addObserver(self, selector: #selector(MCPostListViewController.reachabilityChanged(_:)), name: NSNotification.Name.reachabilityChanged, object: nil) + reach?.startNotifier() self.setupSocket(); } - func reachabilityChanged(notif:NSNotification) { + func reachabilityChanged(_ notif:Notification) { let reach=notif.object as! Reachability; reach.isReachable() ? self.setupSocket() : self.teardownSocket(); } @@ -141,9 +141,9 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl func handleDisconnect() { self.postViewController!.textfield.resignFirstResponder() - self.postViewController!.textfield.enabled=false + self.postViewController!.textfield.isEnabled=false self.postViewController!.setPlaceHolder("Disconnected, please hold") - self.activeCount.hidden = true + self.activeCount.isHidden = true } @@ -157,33 +157,33 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl self.tableView.reloadData() } - func addPost(args:NSArray) { - if let fingerprint=args[0]["fingerprint"] as? String { + func addPost(_ args:NSArray) { + if let fingerprint=(args[0] as! NSDictionary)["fingerprint"] as? String { if(self.blocked.keys.contains(fingerprint)) { return; } self.tableView.beginUpdates() if self.items.count > 0 { for i in 0 ... (self.items.count - 1) { - if let post=self.items.objectAtIndex(i) as? MCPost { + if let post=self.items.object(at: i) as? MCPost { if post.isObsolete() { post.cleanup() - self.items.removeObjectAtIndex(i) - let indexPath=NSIndexPath(forItem: i, inSection: 0) - self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:UITableViewRowAnimation.Automatic) + self.items.removeObject(at: i) + let indexPath=IndexPath(item: i, section: 0) + self.tableView.deleteRows(at: [indexPath], with:UITableViewRowAnimation.automatic) } } } } self.tableView.endUpdates() - if let key = args[0]["key"] as? String { + if let key = (args[0] as! NSDictionary)["key"] as? String { if((self.seen[key] ) != nil) { return; } - self.seen[key]="1" + self.seen[key]="1" as AnyObject? } } let post=MCPost(dict: args[0] as! NSDictionary) - self.items.addObject(post) - let newRow=NSIndexPath(forItem: self.items.count-1, inSection: 0) + self.items.add(post) + let newRow=IndexPath(item: self.items.count-1, section: 0) CATransaction.begin() CATransaction.setCompletionBlock({ @@ -192,7 +192,7 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl } }) self.tableView.beginUpdates() - self.tableView.insertRowsAtIndexPaths([newRow], withRowAnimation: UITableViewRowAnimation.Fade) + self.tableView.insertRows(at: [newRow], with: UITableViewRowAnimation.fade) self.tableView.endUpdates() CATransaction.commit() } @@ -201,77 +201,77 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl self.postViewController!.closePostWithPosted(false) } - func keyboardDidShow(sender:NSNotification) { + func keyboardDidShow(_ sender:Notification) { - let frame = sender.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue - self.containerBottom.constant = frame.size.height + let frame = (sender.userInfo![UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue + self.containerBottom.constant = (frame?.size.height)! self.containerView.setNeedsUpdateConstraints() - UIView.animateWithDuration(0.25, animations: { + UIView.animate(withDuration: 0.25, animations: { self.containerView.layoutIfNeeded() self.containerHeight.constant = 75.0 - self.postViewController!.characterCount.hidden=false - }) { (finished) in + self.postViewController!.characterCount.isHidden=false + }, completion: { (finished) in if self.items.count > 0 { self.scrollToBottom() self.atBottom=true } - } + }) } - func keyboardWillHide(sender:NSNotification) { + func keyboardWillHide(_ sender:Notification) { self.containerBottom.constant = 0; self.containerView.setNeedsUpdateConstraints() - UIView.animateWithDuration(0.25, animations: { + UIView.animate(withDuration: 0.25, animations: { self.containerView.layoutIfNeeded() self.containerHeight.constant = 35.0 - }) { (finished) in + }, completion: { (finished) in if self.items.count > 0 { self.scrollToBottom() - let indexPath=NSIndexPath(forItem: self.items.count-1, inSection: 0) - self.tableView.reloadRowsAtIndexPaths( [indexPath], withRowAnimation: UITableViewRowAnimation.None ) + let indexPath=IndexPath(item: self.items.count-1, section: 0) + self.tableView.reloadRows( at: [indexPath], with: UITableViewRowAnimation.none ) self.atBottom=true } - } + }) } - @IBAction func unblockClicked(sender:AnyObject) { + @IBAction func unblockClicked(_ sender:AnyObject) { self.blocked=[:] - NSUserDefaults.standardUserDefaults().setObject(self.blocked, forKey:"meatspaceBlocks") - self.blockButton.hidden=true + UserDefaults.standard.set(self.blocked, forKey:"meatspaceBlocks") + self.blockButton.isHidden=true } - @IBAction func blockClicked(sender:AnyObject) { - if let blockPost=self.items.objectAtIndex(sender.tag) as? MCPost { - self.blocked[blockPost.fingerprint]="1" - self.blockButton.hidden=false - NSUserDefaults.standardUserDefaults().setObject(self.blocked, forKey: "meatspaceBlocks") + @IBAction func blockClicked(_ sender:AnyObject) { + if let blockPost=self.items.object(at: sender.tag) as? MCPost { + self.blocked[blockPost.fingerprint]="1" as AnyObject + self.blockButton.isHidden=false + UserDefaults.standard.set(self.blocked, forKey: "meatspaceBlocks") for i in 0 ... self.items.count-1{ - if let post = self.items.objectAtIndex(i) as? MCPost { + if let post = self.items.object(at: i) as? MCPost { if post.fingerprint == blockPost.fingerprint { - self.items.removeObject(post) + self.items.remove(post) self.tableView.reloadData() } } } weak var weakSelf=self - let alertController = UIAlertController(title: "Report abuse?", message: "You have just chosen to block another meatspacer. Would you like to report this user for objectionable content?", preferredStyle: UIAlertControllerStyle.Alert) - let cancelAction=UIAlertAction(title: "No", style: UIAlertActionStyle.Cancel) { (action) in + let alertController = UIAlertController(title: "Report abuse?", message: "You have just chosen to block another meatspacer. Would you like to report this user for objectionable content?", preferredStyle: UIAlertControllerStyle.alert) + let cancelAction=UIAlertAction(title: "No", style: UIAlertActionStyle.cancel) { (action) in } - let okAction=UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default) { (action) in + let okAction=UIAlertAction(title: "Yes", style: UIAlertActionStyle.default) { (action) in let mf=MFMailComposeViewController() mf.setToRecipients(["report@meatspac.es"]); mf.mailComposeDelegate=weakSelf; mf.setSubject(String(format: "Abuse from user fingerprint %@",blockPost.fingerprint)); - weakSelf!.presentViewController(mf, animated: true, completion: {}) + weakSelf!.present(mf, animated: true, completion: {}) } alertController.addAction(cancelAction) alertController.addAction(okAction) - self.presentViewController(alertController, animated:true, completion:nil); + self.present(alertController, animated:true, completion:nil); } @@ -284,47 +284,47 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl self.postViewController!.setPlaceHolder("Connecting to meatspace") - SIOSocket.socketWithHost(NSUserDefaults.standardUserDefaults().objectForKey("server_url") as? String, response: { (sock) in + SIOSocket.socket(withHost: UserDefaults.standard.object(forKey: "server_url") as? String, response: { (sock) in self.socket=sock self.socket!.onConnect = { weakSelf?.socket!.emit("join", args: ["mp4"]) - dispatch_async(dispatch_get_main_queue(), { - weakSelf?.postViewController!.textfield.enabled=true + DispatchQueue.main.async(execute: { + weakSelf?.postViewController!.textfield.isEnabled=true weakSelf?.postViewController!.setRandomPlaceholder() }) } self.socket!.onDisconnect = { - dispatch_async(dispatch_get_main_queue(), { + DispatchQueue.main.async(execute: { weakSelf?.handleDisconnect() }) } self.socket!.on("message", callback: { (data) in - dispatch_async(dispatch_get_main_queue(), { - weakSelf!.addPost(data) + DispatchQueue.main.async(execute: { + weakSelf!.addPost(data as! NSArray) }) }) self.socket!.on("messageack", callback: { (data) in - if let message=data[0] as? String { - dispatch_async(dispatch_get_main_queue(), { + if let message=data?[0] as? String { + DispatchQueue.main.async(execute: { weakSelf?.postViewController!.setPlaceHolder(message) - if let uid=data[1]["userId"] as? String { + if let uid=(data?[1] as! NSDictionary)["userId"] as? String { self.userId=uid } }) } }) self.socket!.on("active", callback: { (args) in - dispatch_async(dispatch_get_main_queue(), { - self.activeCount.text=args[0].stringValue - self.activeCount.hidden=false + DispatchQueue.main.async(execute: { + self.activeCount.text=(args?[0] as AnyObject).stringValue + self.activeCount.isHidden=false }) }) self.socket!.onError = { (errorInfo) in print(errorInfo) - dispatch_async(dispatch_get_main_queue(), { - weakSelf?.postViewController!.setPlaceHolder(String(format: "An error occured: %@",errorInfo)) + DispatchQueue.main.async(execute: { + weakSelf?.postViewController!.setPlaceHolder(String(format: "An error occured: %@", errorInfo!)) }) } self.socket!.onReconnect = { (numberOfAttempts) in @@ -332,75 +332,75 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl } self.socket!.onReconnectionAttempt = { (numberOfAttempts) in print(String(format: "Attempt %ld",numberOfAttempts)) - dispatch_async(dispatch_get_main_queue(), { + DispatchQueue.main.async(execute: { weakSelf?.postViewController!.setPlaceHolder("Reconnecting to meatspace.") }) } self.socket!.onReconnectionError={ (errorInfo) in print(errorInfo) - dispatch_async(dispatch_get_main_queue(), { - weakSelf!.postViewController!.setPlaceHolder(String(format: "Could not connect: %@",errorInfo)) + DispatchQueue.main.async(execute: { + weakSelf!.postViewController!.setPlaceHolder(String(format: "Could not connect: %@", errorInfo!)) }) } }) } - func numberOfSectionsInTableView(tableView: UITableView) -> Int { + func numberOfSections(in tableView: UITableView) -> Int { return 1 } - func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } - func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { - if let cell=tableView.dequeueReusableCellWithIdentifier("MeatCell", forIndexPath: indexPath) as? MCPostCell { - if let post=self.items.objectAtIndex(indexPath.row) as? MCPost { + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + if let cell=tableView.dequeueReusableCell(withIdentifier: "MeatCell", for: indexPath) as? MCPostCell { + if let post=self.items.object(at: indexPath.row) as? MCPost { cell.textView.attributedText=post.attributedString cell.timeLabel.text=post.relativeTime() if self.userId == post.fingerprint { - self.blockButton.hidden=true + self.blockButton.isHidden=true } else { - cell.blockButton.hidden=false + cell.blockButton.isHidden=false cell.blockButton.tag=indexPath.row } - let item=AVPlayerItem(URL: post.videoUrl) - cell.videoPlayer?.replaceCurrentItemWithPlayerItem(item) + let item=AVPlayerItem(url: post.videoUrl as URL) + cell.videoPlayer?.replaceCurrentItem(with: item) if self.items.count-1 == self.tableView.visibleCells.count { cell.videoPlayer?.play() } - NSNotificationCenter.defaultCenter().addObserver(cell, selector: #selector(cell.playerItemDidReachEnd(_:)), name: AVPlayerItemDidPlayToEndTimeNotification, object: item) + NotificationCenter.default.addObserver(cell, selector: #selector(cell.playerItemDidReachEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item) } return cell } return UITableViewCell() } - func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { + func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let postCell=cell as? MCPostCell { postCell.videoPlayer!.pause() } } - func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { - if let cell=tableView.cellForRowAtIndexPath(indexPath) as? MCPostCell { - cell.blockButton.hidden=true + func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { + if let cell=tableView.cellForRow(at: indexPath) as? MCPostCell { + cell.blockButton.isHidden=true } } - func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { - if let cell=tableView.cellForRowAtIndexPath(indexPath) as? MCPostCell { - cell.blockButton.hidden=false + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + if let cell=tableView.cellForRow(at: indexPath) as? MCPostCell { + cell.blockButton.isHidden=false } } - func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { + func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { return true } - func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { - self.dismissViewControllerAnimated(true) {} + func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { + self.dismiss(animated: true) {} } } diff --git a/MeatChat/MCPostViewController.swift b/MeatChat/MCPostViewController.swift index b9d650d..f74fd2a 100644 --- a/MeatChat/MCPostViewController.swift +++ b/MeatChat/MCPostViewController.swift @@ -52,8 +52,8 @@ class MCPostViewController : UIViewController, AVCaptureVideoDataOutputSampleBuf self.setPlaceHolder(titles[Int(index)]) } - func setPlaceHolder(title:String) { - self.textfield.attributedPlaceholder = NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIColor.darkGrayColor()]) + func setPlaceHolder(_ title:String) { + self.textfield.attributedPlaceholder = NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIColor.darkGray]) } @@ -66,7 +66,7 @@ class MCPostViewController : UIViewController, AVCaptureVideoDataOutputSampleBuf session.sessionPreset = AVCaptureSessionPresetMedium // Find a suitable AVCaptureDevice - let device = self.cameraWithPosition(AVCaptureDevicePosition.Front); + let device = self.cameraWithPosition(AVCaptureDevicePosition.front); do { @@ -92,18 +92,18 @@ class MCPostViewController : UIViewController, AVCaptureVideoDataOutputSampleBuf session.addOutput(output) self.switchCameraTapped(self); let captureLayer = AVCaptureVideoPreviewLayer(session: session) - captureLayer.frame = self.imageButton.bounds - captureLayer.videoGravity=AVLayerVideoGravityResizeAspectFill + captureLayer?.frame = self.imageButton.bounds + captureLayer?.videoGravity=AVLayerVideoGravityResizeAspectFill - self.imageButton.layer.addSublayer(captureLayer) + self.imageButton.layer.addSublayer(captureLayer!) self.captureLayer=captureLayer; // Configure your output. - let queue = dispatch_queue_create("myQueue", nil); + let queue = DispatchQueue(label: "myQueue", attributes: []); output.setSampleBufferDelegate(self, queue: queue) // Specify the pixel format - output.videoSettings = [kCVPixelBufferPixelFormatTypeKey: NSNumber(unsignedInt: kCVPixelFormatType_32BGRA)] + output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable: NSNumber(value: kCVPixelFormatType_32BGRA as UInt32)] // Assign session to an ivar. @@ -112,9 +112,9 @@ class MCPostViewController : UIViewController, AVCaptureVideoDataOutputSampleBuf // Find a camera with the specified AVCaptureDevicePosition, returning nil if one is not found - func cameraWithPosition(position:AVCaptureDevicePosition) -> AVCaptureDevice { - let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) - for device in devices { + func cameraWithPosition(_ position:AVCaptureDevicePosition) -> AVCaptureDevice { + let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) + for device in devices! { if let avdev = device as? AVCaptureDevice { if avdev.position == position { return avdev @@ -124,7 +124,7 @@ class MCPostViewController : UIViewController, AVCaptureVideoDataOutputSampleBuf return AVCaptureDevice() } - @IBAction func switchCameraTapped(sender:AnyObject) { + @IBAction func switchCameraTapped(_ sender:AnyObject) { if (session != nil) { //Indicate that some changes will be made to the session @@ -138,24 +138,24 @@ class MCPostViewController : UIViewController, AVCaptureVideoDataOutputSampleBuf session!.removeInput(camera) //Get new input - if camera!.device.position == AVCaptureDevicePosition.Back { + if camera!.device.position == AVCaptureDevicePosition.back { do { - flashButton.selected=false; + flashButton.isSelected=false; try camera!.device.lockForConfiguration() - if camera!.device.isTorchModeSupported(AVCaptureTorchMode.Off) { - camera!.device.torchMode=AVCaptureTorchMode.Off; + if camera!.device.isTorchModeSupported(AVCaptureTorchMode.off) { + camera!.device.torchMode=AVCaptureTorchMode.off; } camera!.device.unlockForConfiguration(); - newCamera = self.cameraWithPosition(AVCaptureDevicePosition.Front); + newCamera = self.cameraWithPosition(AVCaptureDevicePosition.front); } catch { print(error) } } else { - newCamera = self.cameraWithPosition(AVCaptureDevicePosition.Back); + newCamera = self.cameraWithPosition(AVCaptureDevicePosition.back); } //Add input to session @@ -177,24 +177,24 @@ class MCPostViewController : UIViewController, AVCaptureVideoDataOutputSampleBuf } - func closePostWithPosted(posted:Bool) { + func closePostWithPosted(_ posted:Bool) { self.textfield.resignFirstResponder() if(posted) { self.textfield.text="" self.characterCount.text="250 left" self.setRandomPlaceholder() } - self.countLabel.hidden=true; + self.countLabel.isHidden=true; self.countLabel.text="9"; - self.characterCount.hidden=true; - UIView.animateWithDuration(0.5) { + self.characterCount.isHidden=true; + UIView.animate(withDuration: 0.5, animations: { self.imageButton.alpha=0; - } + }) session?.stopRunning() } - func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) { + func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) { if self.capturing { // FIXME: This is a dirty hack, because CAPTURE_FRAMES_PER_SECOND above doesn't seem to work. @@ -202,35 +202,35 @@ class MCPostViewController : UIViewController, AVCaptureVideoDataOutputSampleBuf self.skipFrames -= 1; return; } - dispatch_async(dispatch_get_main_queue(), { self.updateCount() }) + DispatchQueue.main.async(execute: { self.updateCount() }) self.skipFrames=5; - self.frames.addObject(self.imageFromSampleBuffer(sampleBuffer)); + self.frames.add(self.imageFromSampleBuffer(sampleBuffer)); if self.frames.count == 10 { let encodedImages=NSMutableArray() for i in 0 ..< self.frames.count { var image=self.frames[i] as? UIImage - image=image!.imageByScalingAndCroppingForSize(CGSizeMake(200, 150)) + image=image!.imageByScalingAndCroppingForSize(CGSize(width: 200, height: 150)) let imageData = UIImageJPEGRepresentation(image!, 0.6); - let encodedString = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength) - encodedImages.addObject(String(format: "data:image/jpeg;base64,%@", encodedString)) + let encodedString = imageData!.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters) + encodedImages.add(String(format: "data:image/jpeg;base64,%@", encodedString)) } self.capturing=false self.frames.removeAllObjects() - let parentViewController=self.parentViewController as? MCPostListViewController + let parentViewController=self.parent as? MCPostListViewController - var uuid:String = UIDevice.currentDevice().identifierForVendor!.UUIDString - uuid=uuid.stringByReplacingOccurrencesOfString("-", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) - let index = uuid.startIndex.advancedBy(15) - uuid=uuid.substringToIndex(index).lowercaseString + var uuid:String = UIDevice.current.identifierForVendor!.uuidString + uuid=uuid.replacingOccurrences(of: "-", with: "", options: NSString.CompareOptions.literal, range: nil) + let index = uuid.characters.index(uuid.startIndex, offsetBy: 15) + uuid=uuid.substring(to: index).lowercased() let message = [ "fingerprint": uuid, "message": self.textfield.text!, "media": encodedImages - ] - dispatch_async(dispatch_get_main_queue(), { + ] as [String : Any] + DispatchQueue.main.async(execute: { parentViewController!.socket!.emit("message", args: [message]) self.closePostWithPosted(true) }) @@ -239,11 +239,11 @@ class MCPostViewController : UIViewController, AVCaptureVideoDataOutputSampleBuf } - func imageFromSampleBuffer(sampleBuffer:CMSampleBufferRef) -> UIImage { + func imageFromSampleBuffer(_ sampleBuffer:CMSampleBuffer) -> UIImage { // Get a CMSampleBuffer's Core Video image buffer for the media data let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) // Lock the base address of the pixel buffer - CVPixelBufferLockBaseAddress(imageBuffer!, 0); + CVPixelBufferLockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0))); // Get the number of bytes per row for the pixel buffer let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer!) @@ -259,53 +259,53 @@ class MCPostViewController : UIViewController, AVCaptureVideoDataOutputSampleBuf // Create a bitmap graphics context with the sample buffer data - let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue) + let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) - let context = CGBitmapContextCreate(baseAddress, width, height, 8, - bytesPerRow, colorSpace, bitmapInfo.rawValue) + let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8, + bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) - let quartzImage = CGBitmapContextCreateImage(context) + let quartzImage = context!.makeImage() // Unlock the pixel buffer - CVPixelBufferUnlockBaseAddress(imageBuffer!,0) + CVPixelBufferUnlockBaseAddress(imageBuffer!,CVPixelBufferLockFlags(rawValue: CVOptionFlags(0))) // Create an image object from the Quartz image let currentCameraInput = session!.inputs[0] let camera=currentCameraInput as? AVCaptureDeviceInput - let frontcamera:Bool = camera!.device.position == AVCaptureDevicePosition.Front - let image = UIImage(CGImage: quartzImage!, scale:1.0, orientation: self.currentImageOrientationWithMirroring(frontcamera)) + let frontcamera:Bool = camera!.device.position == AVCaptureDevicePosition.front + let image = UIImage(cgImage: quartzImage!, scale:1.0, orientation: self.currentImageOrientationWithMirroring(frontcamera)) return (image); } - func currentImageOrientationWithMirroring(isUsingFrontCamera:Bool) -> UIImageOrientation { - switch UIDevice.currentDevice().orientation { - case UIDeviceOrientation.Portrait: - return isUsingFrontCamera ? UIImageOrientation.Right : UIImageOrientation.LeftMirrored - case UIDeviceOrientation.PortraitUpsideDown: - return isUsingFrontCamera ? UIImageOrientation.Left :UIImageOrientation.RightMirrored - case UIDeviceOrientation.LandscapeLeft: - return isUsingFrontCamera ? UIImageOrientation.Down : UIImageOrientation.UpMirrored - case UIDeviceOrientation.LandscapeRight: - return isUsingFrontCamera ? UIImageOrientation.Up : UIImageOrientation.DownMirrored + func currentImageOrientationWithMirroring(_ isUsingFrontCamera:Bool) -> UIImageOrientation { + switch UIDevice.current.orientation { + case UIDeviceOrientation.portrait: + return isUsingFrontCamera ? UIImageOrientation.right : UIImageOrientation.leftMirrored + case UIDeviceOrientation.portraitUpsideDown: + return isUsingFrontCamera ? UIImageOrientation.left :UIImageOrientation.rightMirrored + case UIDeviceOrientation.landscapeLeft: + return isUsingFrontCamera ? UIImageOrientation.down : UIImageOrientation.upMirrored + case UIDeviceOrientation.landscapeRight: + return isUsingFrontCamera ? UIImageOrientation.up : UIImageOrientation.downMirrored default: - return UIImageOrientation.Up + return UIImageOrientation.up } } - func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { - let oldLength = textField.text?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) - let replacementLength = string.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) + func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { + let oldLength = textField.text?.lengthOfBytes(using: String.Encoding.utf8) + let replacementLength = string.lengthOfBytes(using: String.Encoding.utf8) let rangeLength = range.length let newLength = oldLength! - rangeLength + replacementLength - let returnKey:Bool = string.containsString("\n") + let returnKey:Bool = string.contains("\n") if( newLength <= MAXLENGTH) { self.characterCount.text=String(format: "%lu left",MAXLENGTH-newLength) } @@ -313,60 +313,60 @@ class MCPostViewController : UIViewController, AVCaptureVideoDataOutputSampleBuf } - func textFieldShouldBeginEditing(textField: UITextField) -> Bool { + func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { session!.startRunning() - UIView.animateWithDuration(0.5, animations: { + UIView.animate(withDuration: 0.5, animations: { self.imageButton.alpha=1 - }) { (finished) in + }, completion: { (finished) in self.textfield.becomeFirstResponder() - } + }) return true; } - func textFieldShouldReturn(textField: UITextField) -> Bool { - self.countLabel.hidden=false + func textFieldShouldReturn(_ textField: UITextField) -> Bool { + self.countLabel.isHidden=false self.capturing=true return true } - override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { + override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { self.orientationChanged() } func orientationChanged() { // get the new orientation from device - let newOrientation = self.videoOrientationFromDeviceOrientation(UIDevice.currentDevice().orientation); + let newOrientation = self.videoOrientationFromDeviceOrientation(UIDevice.current.orientation); // set the orientation of preview layer :( which will be displayed in the device ) self.captureLayer!.connection.videoOrientation = newOrientation } - func videoOrientationFromDeviceOrientation(deviceOrientation:UIDeviceOrientation) -> AVCaptureVideoOrientation { + func videoOrientationFromDeviceOrientation(_ deviceOrientation:UIDeviceOrientation) -> AVCaptureVideoOrientation { var orientation:AVCaptureVideoOrientation switch (deviceOrientation) { - case UIDeviceOrientation.Unknown: - orientation = AVCaptureVideoOrientation.Portrait; + case UIDeviceOrientation.unknown: + orientation = AVCaptureVideoOrientation.portrait; break - case UIDeviceOrientation.Portrait: - orientation = AVCaptureVideoOrientation.Portrait + case UIDeviceOrientation.portrait: + orientation = AVCaptureVideoOrientation.portrait break; - case UIDeviceOrientation.PortraitUpsideDown: - orientation = AVCaptureVideoOrientation.PortraitUpsideDown; + case UIDeviceOrientation.portraitUpsideDown: + orientation = AVCaptureVideoOrientation.portraitUpsideDown; break; - case UIDeviceOrientation.LandscapeLeft: - orientation = AVCaptureVideoOrientation.LandscapeRight + case UIDeviceOrientation.landscapeLeft: + orientation = AVCaptureVideoOrientation.landscapeRight break; - case UIDeviceOrientation.LandscapeRight: - orientation = AVCaptureVideoOrientation.LandscapeLeft; + case UIDeviceOrientation.landscapeRight: + orientation = AVCaptureVideoOrientation.landscapeLeft; break; - case UIDeviceOrientation.FaceUp: - orientation = AVCaptureVideoOrientation.Portrait; + case UIDeviceOrientation.faceUp: + orientation = AVCaptureVideoOrientation.portrait; break; - case UIDeviceOrientation.FaceDown: - orientation = AVCaptureVideoOrientation.Portrait; + case UIDeviceOrientation.faceDown: + orientation = AVCaptureVideoOrientation.portrait; } return orientation; } diff --git a/MeatChat/MeatChat2-Info.plist b/MeatChat/MeatChat2-Info.plist index aa6f0fa..4eeb484 100644 --- a/MeatChat/MeatChat2-Info.plist +++ b/MeatChat/MeatChat2-Info.plist @@ -2,6 +2,8 @@ + NSCameraUsageDescription + Used to show your beautiful face with your chat messages CFBundleDevelopmentRegion en CFBundleDisplayName diff --git a/MeatChat/UIImage-Scaled.swift b/MeatChat/UIImage-Scaled.swift index 0a0df3f..4f54655 100644 --- a/MeatChat/UIImage-Scaled.swift +++ b/MeatChat/UIImage-Scaled.swift @@ -9,7 +9,7 @@ import Foundation extension UIImage { - func imageByScalingAndCroppingForSize(targetSize:CGSize) -> UIImage { + func imageByScalingAndCroppingForSize(_ targetSize:CGSize) -> UIImage { let sourceImage = self let imageSize = sourceImage.size @@ -17,12 +17,12 @@ extension UIImage { let height = imageSize.height let targetWidth = targetSize.width let targetHeight = targetSize.height - var thumbnailPoint = CGPointMake(0.0,0.0) + var thumbnailPoint = CGPoint(x: 0.0,y: 0.0) var scaleFactor = 0.0; var scaledWidth = targetWidth var scaledHeight = targetHeight - if CGSizeEqualToSize(imageSize, targetSize) == false { + if imageSize.equalTo(targetSize) == false { let widthFactor = Double(targetWidth / width) let heightFactor = Double(targetHeight / height) @@ -52,12 +52,12 @@ extension UIImage { UIGraphicsBeginImageContext(targetSize) // this will crop - var thumbnailRect = CGRectZero + var thumbnailRect = CGRect.zero thumbnailRect.origin = thumbnailPoint thumbnailRect.size.width = scaledWidth thumbnailRect.size.height = scaledHeight - sourceImage.drawInRect(thumbnailRect) + sourceImage.draw(in: thumbnailRect) let newImage = UIGraphicsGetImageFromCurrentImageContext() @@ -65,6 +65,6 @@ extension UIImage { //pop the context to get back to the default UIGraphicsEndImageContext() - return newImage + return newImage! } -} \ No newline at end of file +} diff --git a/MeatChat2.xcodeproj/project.pbxproj b/MeatChat2.xcodeproj/project.pbxproj index 4527e32..8419edd 100644 --- a/MeatChat2.xcodeproj/project.pbxproj +++ b/MeatChat2.xcodeproj/project.pbxproj @@ -27,12 +27,12 @@ 2CEB7CDB1CA1ECFD0038D78B /* NMViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CEB7CDA1CA1ECFD0038D78B /* NMViewController.swift */; }; 2CEB7CDD1CA1ED6E0038D78B /* MCPostListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CEB7CDC1CA1ED6E0038D78B /* MCPostListViewController.swift */; }; 2CEB7CDF1CA1EE320038D78B /* MCPostViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CEB7CDE1CA1EE320038D78B /* MCPostViewController.swift */; }; - 61B37259671C453AA69C08CE /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 24400EDD099742C5ABF721BF /* libPods.a */; }; + 96560009540BEDE390D7E2CD /* libPods-MeatChat2.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 446AF5B82104E54D6B462C5C /* libPods-MeatChat2.a */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 0B3A5579DCBE51281B607C29 /* Pods-MeatChat2.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MeatChat2.debug.xcconfig"; path = "Pods/Target Support Files/Pods-MeatChat2/Pods-MeatChat2.debug.xcconfig"; sourceTree = ""; }; 22771F1B1A0D171900D93C65 /* DefaultDefaults.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = DefaultDefaults.plist; sourceTree = ""; }; - 24400EDD099742C5ABF721BF /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; }; 2C1F8C991885CFEB001BE713 /* MeatChat2.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = MeatChat2.app; sourceTree = BUILT_PRODUCTS_DIR; }; 2C1F8C9C1885CFEB001BE713 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 2C1F8C9E1885CFEB001BE713 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; @@ -61,8 +61,8 @@ 2CEB7CDC1CA1ED6E0038D78B /* MCPostListViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MCPostListViewController.swift; sourceTree = ""; }; 2CEB7CDE1CA1EE320038D78B /* MCPostViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MCPostViewController.swift; sourceTree = ""; }; 4134EA2819E9EC210093B991 /* MeatChat2-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "MeatChat2-Prefix.pch"; path = "MeatChat/MeatChat2-Prefix.pch"; sourceTree = ""; }; - 878D885A722FC2C12257BA5B /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.release.xcconfig; path = "Pods/Target Support Files/Pods/Pods.release.xcconfig"; sourceTree = ""; }; - BB118653E2E1DB891F4CA8C6 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = ""; }; + 446AF5B82104E54D6B462C5C /* libPods-MeatChat2.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-MeatChat2.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + 5260C9FBCB585DBE7D0609EC /* Pods-MeatChat2.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MeatChat2.release.xcconfig"; path = "Pods/Target Support Files/Pods-MeatChat2/Pods-MeatChat2.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -76,7 +76,7 @@ 2C1F8CFD1885FB86001BE713 /* libicucore.dylib in Frameworks */, 2C1F8C9F1885CFEB001BE713 /* CoreGraphics.framework in Frameworks */, 2C1F8CA11885CFEB001BE713 /* UIKit.framework in Frameworks */, - 61B37259671C453AA69C08CE /* libPods.a in Frameworks */, + 96560009540BEDE390D7E2CD /* libPods-MeatChat2.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -90,7 +90,7 @@ 2C1F8CA21885CFEB001BE713 /* MeatChat */, 2C1F8C9B1885CFEB001BE713 /* Frameworks */, 2C1F8C9A1885CFEB001BE713 /* Products */, - 30709C7767B2121A7B0101B4 /* Pods */, + D6355BCB586F93F10044B489 /* Pods */, ); sourceTree = ""; }; @@ -112,7 +112,7 @@ 2C1F8C9E1885CFEB001BE713 /* CoreGraphics.framework */, 2C1F8CA01885CFEB001BE713 /* UIKit.framework */, 2C1F8CBE1885CFEB001BE713 /* XCTest.framework */, - 24400EDD099742C5ABF721BF /* libPods.a */, + 446AF5B82104E54D6B462C5C /* libPods-MeatChat2.a */, ); name = Frameworks; sourceTree = ""; @@ -184,11 +184,11 @@ name = Models; sourceTree = ""; }; - 30709C7767B2121A7B0101B4 /* Pods */ = { + D6355BCB586F93F10044B489 /* Pods */ = { isa = PBXGroup; children = ( - BB118653E2E1DB891F4CA8C6 /* Pods.debug.xcconfig */, - 878D885A722FC2C12257BA5B /* Pods.release.xcconfig */, + 0B3A5579DCBE51281B607C29 /* Pods-MeatChat2.debug.xcconfig */, + 5260C9FBCB585DBE7D0609EC /* Pods-MeatChat2.release.xcconfig */, ); name = Pods; sourceTree = ""; @@ -200,12 +200,12 @@ isa = PBXNativeTarget; buildConfigurationList = 2C1F8CCE1885CFEB001BE713 /* Build configuration list for PBXNativeTarget "MeatChat2" */; buildPhases = ( - BBA07FE4852D4CF2954B2AB4 /* Check Pods Manifest.lock */, + 1E5A10AE3689AA376815379C /* 📦 Check Pods Manifest.lock */, 2C1F8C951885CFEB001BE713 /* Sources */, 2C1F8C961885CFEB001BE713 /* Frameworks */, 2C1F8C971885CFEB001BE713 /* Resources */, - CF0CBC43598E48318E5B1E58 /* Copy Pods Resources */, - 41F99944D11ECDBE143167A1 /* Embed Pods Frameworks */, + 5D18196378DD0A1442FE9BDA /* 📦 Embed Pods Frameworks */, + 97C4190E4C1FABDFCF2037B6 /* 📦 Copy Pods Resources */, ); buildRules = ( ); @@ -223,11 +223,13 @@ isa = PBXProject; attributes = { CLASSPREFIX = NM; - LastUpgradeCheck = 0720; + LastUpgradeCheck = 0800; ORGANIZATIONNAME = "Nordaaker AS"; TargetAttributes = { 2C1F8C981885CFEB001BE713 = { - DevelopmentTeam = SVJ2962KBR; + DevelopmentTeam = JGL7Q3WM83; + LastSwiftMigration = 0830; + ProvisioningStyle = Automatic; }; }; }; @@ -266,49 +268,49 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 41F99944D11ECDBE143167A1 /* Embed Pods Frameworks */ = { + 1E5A10AE3689AA376815379C /* 📦 Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Embed Pods Frameworks"; + name = "📦 Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods/Pods-frameworks.sh\"\n"; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - BBA07FE4852D4CF2954B2AB4 /* Check Pods Manifest.lock */ = { + 5D18196378DD0A1442FE9BDA /* 📦 Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Check Pods Manifest.lock"; + name = "📦 Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-MeatChat2/Pods-MeatChat2-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - CF0CBC43598E48318E5B1E58 /* Copy Pods Resources */ = { + 97C4190E4C1FABDFCF2037B6 /* 📦 Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Copy Pods Resources"; + name = "📦 Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods/Pods-resources.sh\"\n"; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-MeatChat2/Pods-MeatChat2-resources.sh\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ @@ -373,14 +375,19 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", @@ -393,7 +400,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; @@ -413,21 +420,27 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = YES; ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -435,7 +448,7 @@ }; 2C1F8CCF1885CFEB001BE713 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = BB118653E2E1DB891F4CA8C6 /* Pods.debug.xcconfig */; + baseConfigurationReference = 0B3A5579DCBE51281B607C29 /* Pods-MeatChat2.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; @@ -451,6 +464,7 @@ PROVISIONING_PROFILE = ""; SWIFT_OBJC_BRIDGING_HEADER = "MeatChat/MeatChat-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; WRAPPER_EXTENSION = app; }; @@ -458,7 +472,7 @@ }; 2C1F8CD01885CFEB001BE713 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 878D885A722FC2C12257BA5B /* Pods.release.xcconfig */; + baseConfigurationReference = 5260C9FBCB585DBE7D0609EC /* Pods-MeatChat2.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; @@ -473,6 +487,7 @@ PRODUCT_NAME = MeatChat2; PROVISIONING_PROFILE = ""; SWIFT_OBJC_BRIDGING_HEADER = "MeatChat/MeatChat-Bridging-Header.h"; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; WRAPPER_EXTENSION = app; }; diff --git a/Podfile.lock b/Podfile.lock index 3ab61ed..c114317 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -13,4 +13,6 @@ SPEC CHECKSUMS: Reachability: dd9aa4fb6667b9f787690a74f53cb7634ce99893 SIOSocket: 2facc0bd02ae72d98c223634a46dd8ebdf9be321 -COCOAPODS: 0.39.0 +PODFILE CHECKSUM: c4ad0541c7849b28ec097fc60a960fb2c156b94d + +COCOAPODS: 1.0.0 From 14fbfc0facc7426f53755d10ee0d9aa81b9c7eb8 Mon Sep 17 00:00:00 2001 From: Emily Marigold Klassen Date: Mon, 18 Sep 2017 16:15:27 -0700 Subject: [PATCH 2/2] upgrade to new versions of dependencies --- MeatChat/MCPost.swift | 3 +- MeatChat/MCPostListViewController.swift | 151 ++++++++++++++---------- MeatChat/MCPostViewController.swift | 7 +- MeatChat/MeatChat-Bridging-Header.h | 5 +- MeatChat2.xcodeproj/project.pbxproj | 40 ++++--- Podfile | 10 +- Podfile.lock | 25 ++-- 7 files changed, 145 insertions(+), 96 deletions(-) diff --git a/MeatChat/MCPost.swift b/MeatChat/MCPost.swift index 2f8ac89..a4c815a 100644 --- a/MeatChat/MCPost.swift +++ b/MeatChat/MCPost.swift @@ -8,6 +8,7 @@ import Foundation import UIKit +import DateToolsSwift class MCPost :NSObject { @@ -54,7 +55,7 @@ class MCPost :NSObject { func relativeTime() -> String { let epoch: TimeInterval = Double(created)/1000 let postDate: Date = Date(timeIntervalSince1970: epoch) - return (postDate as NSDate).dateTimeAgo() + return postDate.timeAgoSinceNow } func cleanup() { diff --git a/MeatChat/MCPostListViewController.swift b/MeatChat/MCPostListViewController.swift index b64c23a..f984e47 100644 --- a/MeatChat/MCPostListViewController.swift +++ b/MeatChat/MCPostListViewController.swift @@ -8,7 +8,8 @@ import UIKit import MessageUI.MFMailComposeViewController - +import SocketIO +import ReachabilitySwift class MCPostListViewController : UIViewController, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate, AVAssetResourceLoaderDelegate,MFMailComposeViewControllerDelegate { @@ -26,7 +27,7 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl @IBOutlet weak var activeCount:UILabel! @IBOutlet weak var blockButton:UIButton! - var socket:SIOSocket? + var socket:SocketIOClient? var postViewController:MCPostViewController? var acceptedEula:Bool! @@ -119,22 +120,26 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl func setupReachability() { let server_url=URL(string: UserDefaults.standard.object(forKey: "server_url") as! String); - let reach = Reachability(hostname: server_url!.host); - NotificationCenter.default.addObserver(self, selector: #selector(MCPostListViewController.reachabilityChanged(_:)), name: NSNotification.Name.reachabilityChanged, object: nil) - reach?.startNotifier() - self.setupSocket(); + let reach = Reachability(hostname: server_url!.host!)! + NotificationCenter.default.addObserver(self, selector: #selector(MCPostListViewController.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: nil) + do { + try reach.startNotifier() + } catch { + print("could not start reachability notifier") + } + // self.setupSocket(); } func reachabilityChanged(_ notif:Notification) { let reach=notif.object as! Reachability; - reach.isReachable() ? self.setupSocket() : self.teardownSocket(); + reach.isReachable ? self.setupSocket() : self.teardownSocket(); } func teardownSocket() { - self.socket!.close() + self.socket!.disconnect() self.socket=nil; self.postViewController!.setPlaceHolder("Get the internet, bae.") } @@ -284,66 +289,92 @@ class MCPostListViewController : UIViewController, UITableViewDataSource, UITabl self.postViewController!.setPlaceHolder("Connecting to meatspace") - SIOSocket.socket(withHost: UserDefaults.standard.object(forKey: "server_url") as? String, response: { (sock) in + print("setupSocket") + self.socket = SocketIOClient(socketURL: URL(string: UserDefaults.standard.object(forKey: "server_url") as! String)!) - self.socket=sock - self.socket!.onConnect = { - weakSelf?.socket!.emit("join", args: ["mp4"]) - DispatchQueue.main.async(execute: { - weakSelf?.postViewController!.textfield.isEnabled=true - weakSelf?.postViewController!.setRandomPlaceholder() - }) - } - self.socket!.onDisconnect = { - DispatchQueue.main.async(execute: { - weakSelf?.handleDisconnect() - }) - } - self.socket!.on("message", callback: { (data) in - DispatchQueue.main.async(execute: { - weakSelf!.addPost(data as! NSArray) - }) + self.socket!.on(clientEvent: .connect) { data, ack in + print("join") + weakSelf?.socket!.emit("join", ["mp4"]) + DispatchQueue.main.async(execute: { + weakSelf?.postViewController!.textfield.isEnabled=true + weakSelf?.postViewController!.setRandomPlaceholder() }) - self.socket!.on("messageack", callback: { (data) in - if let message=data?[0] as? String { - DispatchQueue.main.async(execute: { - weakSelf?.postViewController!.setPlaceHolder(message) - if let uid=(data?[1] as! NSDictionary)["userId"] as? String { - self.userId=uid - } - }) - } + ack.with("connected") + } + self.socket!.on(clientEvent: .disconnect) { data, ack in + DispatchQueue.main.async(execute: { + weakSelf?.handleDisconnect() }) - self.socket!.on("active", callback: { (args) in - DispatchQueue.main.async(execute: { - self.activeCount.text=(args?[0] as AnyObject).stringValue - self.activeCount.isHidden=false - }) - + } + self.socket!.on("chat") { data, ack in + let arr = data as NSArray + print(arr.count) + DispatchQueue.main.async(execute: { + print(arr[0] as! NSDictionary) +// print(data[1] as! NSDictionary) }) - self.socket!.onError = { (errorInfo) in - print(errorInfo) - DispatchQueue.main.async(execute: { - weakSelf?.postViewController!.setPlaceHolder(String(format: "An error occured: %@", errorInfo!)) - }) - } - self.socket!.onReconnect = { (numberOfAttempts) in - print(String(format: "Reconnect %ld",numberOfAttempts)) - } - self.socket!.onReconnectionAttempt = { (numberOfAttempts) in - print(String(format: "Attempt %ld",numberOfAttempts)) - DispatchQueue.main.async(execute: { - weakSelf?.postViewController!.setPlaceHolder("Reconnecting to meatspace.") - }) - } - self.socket!.onReconnectionError={ (errorInfo) in - print(errorInfo) + +// DispatchQueue.main.async(execute: { +// if let arr = data as NSArray? { +// weakSelf!.addPost(arr) +// } +// }) + } + self.socket!.on("message") { data, ack in + print(data) + DispatchQueue.main.async(execute: { + let arr = data as NSArray + weakSelf!.addPost(arr) + }) + } + self.socket!.on("messageack") { data, ack in + if let message = (data as NSArray)[0] as? String { DispatchQueue.main.async(execute: { - weakSelf!.postViewController!.setPlaceHolder(String(format: "Could not connect: %@", errorInfo!)) + weakSelf?.postViewController!.setPlaceHolder(message) + if let uid=((data as NSArray)[1] as! NSDictionary)["userId"] as? String { + self.userId=uid + } }) } - }) + } + self.socket!.on("userid") { data, ack in + print(data) + DispatchQueue.main.async(execute: { + if let uid=((data as NSArray)[1] as! NSDictionary)["userId"] as? String { + self.userId=uid + } + }) + } + self.socket!.on("active") { args, ack in + DispatchQueue.main.async(execute: { + self.activeCount.text=((args as NSArray)[0] as AnyObject).stringValue + self.activeCount.isHidden=false + }) + + } + self.socket!.on(clientEvent: .error) { (errorInfo, ack) in + print(errorInfo) + DispatchQueue.main.async(execute: { + weakSelf?.postViewController!.setPlaceHolder(String(format: "An error occured: %@", errorInfo)) + }) + } + self.socket!.on(clientEvent: .reconnect) { numberOfAttempts, ack in + print(String(format: "Reconnect %ld",numberOfAttempts)) + } + self.socket!.on(clientEvent: .reconnectAttempt) { numberOfAttempts, ack in + print(String(format: "Attempt %ld",numberOfAttempts)) + DispatchQueue.main.async(execute: { + weakSelf?.postViewController!.setPlaceHolder("Reconnecting to meatspace.") + }) + } +// self.socket!.onReconnectionError={ (errorInfo) in +// print(errorInfo) +// DispatchQueue.main.async(execute: { +// weakSelf!.postViewController!.setPlaceHolder(String(format: "Could not connect: %@", errorInfo!)) +// }) +// } + self.socket!.connect() } func numberOfSections(in tableView: UITableView) -> Int { diff --git a/MeatChat/MCPostViewController.swift b/MeatChat/MCPostViewController.swift index f74fd2a..7afb9ed 100644 --- a/MeatChat/MCPostViewController.swift +++ b/MeatChat/MCPostViewController.swift @@ -223,15 +223,18 @@ class MCPostViewController : UIViewController, AVCaptureVideoDataOutputSampleBuf var uuid:String = UIDevice.current.identifierForVendor!.uuidString uuid=uuid.replacingOccurrences(of: "-", with: "", options: NSString.CompareOptions.literal, range: nil) - let index = uuid.characters.index(uuid.startIndex, offsetBy: 15) + print("uuid: \(uuid)") + let index = uuid.characters.index(uuid.startIndex, offsetBy: 32) + print("index: \(index)") uuid=uuid.substring(to: index).lowercased() + print("uuid: \(uuid)") let message = [ "fingerprint": uuid, "message": self.textfield.text!, "media": encodedImages ] as [String : Any] DispatchQueue.main.async(execute: { - parentViewController!.socket!.emit("message", args: [message]) + parentViewController!.socket!.emit("message", [message]) self.closePostWithPosted(true) }) } diff --git a/MeatChat/MeatChat-Bridging-Header.h b/MeatChat/MeatChat-Bridging-Header.h index 9285040..185c2a6 100644 --- a/MeatChat/MeatChat-Bridging-Header.h +++ b/MeatChat/MeatChat-Bridging-Header.h @@ -3,9 +3,6 @@ // #import -#import "NSDate+TimeAgo.h" -#import #import #import -#import "Reachability.h" -#import \ No newline at end of file +#import diff --git a/MeatChat2.xcodeproj/project.pbxproj b/MeatChat2.xcodeproj/project.pbxproj index 8419edd..62b5eb0 100644 --- a/MeatChat2.xcodeproj/project.pbxproj +++ b/MeatChat2.xcodeproj/project.pbxproj @@ -27,7 +27,7 @@ 2CEB7CDB1CA1ECFD0038D78B /* NMViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CEB7CDA1CA1ECFD0038D78B /* NMViewController.swift */; }; 2CEB7CDD1CA1ED6E0038D78B /* MCPostListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CEB7CDC1CA1ED6E0038D78B /* MCPostListViewController.swift */; }; 2CEB7CDF1CA1EE320038D78B /* MCPostViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CEB7CDE1CA1EE320038D78B /* MCPostViewController.swift */; }; - 96560009540BEDE390D7E2CD /* libPods-MeatChat2.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 446AF5B82104E54D6B462C5C /* libPods-MeatChat2.a */; }; + D13E3063866A747E46967D67 /* Pods_MeatChat2.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5B3EA209AF642E4074B1C38D /* Pods_MeatChat2.framework */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -61,8 +61,8 @@ 2CEB7CDC1CA1ED6E0038D78B /* MCPostListViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MCPostListViewController.swift; sourceTree = ""; }; 2CEB7CDE1CA1EE320038D78B /* MCPostViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MCPostViewController.swift; sourceTree = ""; }; 4134EA2819E9EC210093B991 /* MeatChat2-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "MeatChat2-Prefix.pch"; path = "MeatChat/MeatChat2-Prefix.pch"; sourceTree = ""; }; - 446AF5B82104E54D6B462C5C /* libPods-MeatChat2.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-MeatChat2.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 5260C9FBCB585DBE7D0609EC /* Pods-MeatChat2.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MeatChat2.release.xcconfig"; path = "Pods/Target Support Files/Pods-MeatChat2/Pods-MeatChat2.release.xcconfig"; sourceTree = ""; }; + 5B3EA209AF642E4074B1C38D /* Pods_MeatChat2.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_MeatChat2.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -76,7 +76,7 @@ 2C1F8CFD1885FB86001BE713 /* libicucore.dylib in Frameworks */, 2C1F8C9F1885CFEB001BE713 /* CoreGraphics.framework in Frameworks */, 2C1F8CA11885CFEB001BE713 /* UIKit.framework in Frameworks */, - 96560009540BEDE390D7E2CD /* libPods-MeatChat2.a in Frameworks */, + D13E3063866A747E46967D67 /* Pods_MeatChat2.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -112,7 +112,7 @@ 2C1F8C9E1885CFEB001BE713 /* CoreGraphics.framework */, 2C1F8CA01885CFEB001BE713 /* UIKit.framework */, 2C1F8CBE1885CFEB001BE713 /* XCTest.framework */, - 446AF5B82104E54D6B462C5C /* libPods-MeatChat2.a */, + 5B3EA209AF642E4074B1C38D /* Pods_MeatChat2.framework */, ); name = Frameworks; sourceTree = ""; @@ -200,12 +200,12 @@ isa = PBXNativeTarget; buildConfigurationList = 2C1F8CCE1885CFEB001BE713 /* Build configuration list for PBXNativeTarget "MeatChat2" */; buildPhases = ( - 1E5A10AE3689AA376815379C /* 📦 Check Pods Manifest.lock */, + 1E5A10AE3689AA376815379C /* [CP] Check Pods Manifest.lock */, 2C1F8C951885CFEB001BE713 /* Sources */, 2C1F8C961885CFEB001BE713 /* Frameworks */, 2C1F8C971885CFEB001BE713 /* Resources */, - 5D18196378DD0A1442FE9BDA /* 📦 Embed Pods Frameworks */, - 97C4190E4C1FABDFCF2037B6 /* 📦 Copy Pods Resources */, + 5D18196378DD0A1442FE9BDA /* [CP] Embed Pods Frameworks */, + 97C4190E4C1FABDFCF2037B6 /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -268,44 +268,56 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 1E5A10AE3689AA376815379C /* 📦 Check Pods Manifest.lock */ = { + 1E5A10AE3689AA376815379C /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-MeatChat2-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; - 5D18196378DD0A1442FE9BDA /* 📦 Embed Pods Frameworks */ = { + 5D18196378DD0A1442FE9BDA /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( + "${SRCROOT}/Pods/Target Support Files/Pods-MeatChat2/Pods-MeatChat2-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/DateToolsSwift/DateToolsSwift.framework", + "${BUILT_PRODUCTS_DIR}/ReachabilitySwift/ReachabilitySwift.framework", + "${BUILT_PRODUCTS_DIR}/Socket.IO-Client-Swift/SocketIO.framework", + "${BUILT_PRODUCTS_DIR}/StarscreamSocketIO/StarscreamSocketIO.framework", ); - name = "📦 Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/DateToolsSwift.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ReachabilitySwift.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SocketIO.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/StarscreamSocketIO.framework", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-MeatChat2/Pods-MeatChat2-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 97C4190E4C1FABDFCF2037B6 /* 📦 Copy Pods Resources */ = { + 97C4190E4C1FABDFCF2037B6 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Copy Pods Resources"; + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Podfile b/Podfile index 237ac88..2d2036b 100644 --- a/Podfile +++ b/Podfile @@ -1,7 +1,9 @@ source 'https://github.com/CocoaPods/Specs.git' +use_frameworks! + target 'MeatChat2' do - pod 'NSDate+TimeAgo' - pod 'SIOSocket', '~> 0.2.0' - pod 'Reachability', '~> 3.1.1' -end \ No newline at end of file + pod 'DateToolsSwift' + pod 'Socket.IO-Client-Swift', '~> 11.1.3' + pod 'ReachabilitySwift', '~> 3' +end diff --git a/Podfile.lock b/Podfile.lock index c114317..f1b352c 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -1,18 +1,21 @@ PODS: - - NSDate+TimeAgo (1.0.3) - - Reachability (3.1.1) - - SIOSocket (0.2.0) + - DateToolsSwift (2.0.3) + - ReachabilitySwift (3) + - Socket.IO-Client-Swift (11.1.3): + - StarscreamSocketIO (~> 8.0.5) + - StarscreamSocketIO (8.0.5) DEPENDENCIES: - - NSDate+TimeAgo - - Reachability (~> 3.1.1) - - SIOSocket (~> 0.2.0) + - DateToolsSwift + - ReachabilitySwift (~> 3) + - Socket.IO-Client-Swift (~> 11.1.3) SPEC CHECKSUMS: - NSDate+TimeAgo: 416f55d2696d3744c313091c5a9280d47f8238fe - Reachability: dd9aa4fb6667b9f787690a74f53cb7634ce99893 - SIOSocket: 2facc0bd02ae72d98c223634a46dd8ebdf9be321 + DateToolsSwift: bf69bf9056d9e53c5c03f06e51f219b9b8b02f9e + ReachabilitySwift: f5b9bb30a0777fac8f09ce8b067e32faeb29bb64 + Socket.IO-Client-Swift: b8e59ddc16bc3609ca2f49a4b50253f095d535c8 + StarscreamSocketIO: b56993332d3cd74885a7486e183ff0cd9541b3f3 -PODFILE CHECKSUM: c4ad0541c7849b28ec097fc60a960fb2c156b94d +PODFILE CHECKSUM: 562e22bfd227911b7416b0ae4e471a73dcef596b -COCOAPODS: 1.0.0 +COCOAPODS: 1.3.1