From 5ec4e1de845ebd58ea8ae5cce3e143f669f8e21e Mon Sep 17 00:00:00 2001 From: nixzhu Date: Thu, 2 Apr 2015 16:28:48 +0800 Subject: [PATCH] try downloadAttachmentOfMessage when see cells --- Yep/Services/YepServiceSync.swift | 43 +++++++++++++++++++ .../ConversationViewController.swift | 2 + 2 files changed, 45 insertions(+) diff --git a/Yep/Services/YepServiceSync.swift b/Yep/Services/YepServiceSync.swift index 0977904d..c69537c8 100644 --- a/Yep/Services/YepServiceSync.swift +++ b/Yep/Services/YepServiceSync.swift @@ -13,6 +13,49 @@ import Realm let YepNewMessagesReceivedNotification = "YepNewMessagesReceivedNotification" +func downloadAttachmentOfMessage(message: Message) { + + func updateMessage(message: Message, withAttachmentFileName attachmentFileName: String) { + let realm = message.realm + realm.beginWriteTransaction() + message.localAttachmentName = attachmentFileName + realm.commitWriteTransaction() + } + + let attachmentURLString = message.attachmentURLString + let localAttachmentName = message.localAttachmentName + + if !attachmentURLString.isEmpty && localAttachmentName.isEmpty { + if let url = NSURL(string: attachmentURLString) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { + let data = NSData(contentsOfURL: url) + + let fileName = NSUUID().UUIDString + + dispatch_async(dispatch_get_main_queue()) { + switch message.mediaType { + case MessageMediaType.Image.rawValue: + if let fileURL = NSFileManager.yepMessageImageURLWithName(fileName) { + updateMessage(message, withAttachmentFileName: fileName) + } + + case MessageMediaType.Video.rawValue: + break // TODO: download video + + case MessageMediaType.Audio.rawValue: + if let fileURL = NSFileManager.yepMessageAudioURLWithName(fileName) { + updateMessage(message, withAttachmentFileName: fileName) + } + + default: + break + } + } + } + } + } +} + func syncFriendshipsAndDoFurtherAction(furtherAction: () -> Void) { friendships { allFriendships in //println("\n allFriendships: \(allFriendships)") diff --git a/Yep/ViewControllers/Conversation/ConversationViewController.swift b/Yep/ViewControllers/Conversation/ConversationViewController.swift index 3fb723eb..3de3813c 100644 --- a/Yep/ViewControllers/Conversation/ConversationViewController.swift +++ b/Yep/ViewControllers/Conversation/ConversationViewController.swift @@ -516,6 +516,8 @@ extension ConversationViewController: UICollectionViewDataSource, UICollectionVi let message = messages.objectAtIndex(UInt(indexPath.row)) as! Message + downloadAttachmentOfMessage(message) + if let sender = message.fromFriend { if sender.friendState != UserFriendState.Me.rawValue { switch message.mediaType {