So I am making this Snapchat look-a-like with stories where it has two stories. First one shows the whole story, and the other one shows the recently added. It's a bit buggy so sometimes when starting up it does not shows the images, but if I close the app and reopen it, it works. And sometimes it shows only some of the image, but it get fixed when close down and reopen the application. Anyways, here is the UIViewController
code:
import Foundation
import UIKit
import Parse
import Player
import AVKit
import AVFoundation
extension NSDate {
func isGreaterThanDate(dateToCompare: NSDate) -> Bool {
//Declare Variables
var isGreater = false
//Compare Values
if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending {
isGreater = true
}
//Return Result
return isGreater
}
func isLessThanDate(dateToCompare: NSDate) -> Bool {
//Declare Variables
var isLess = false
//Compare Values
if self.compare(dateToCompare) == NSComparisonResult.OrderedAscending {
isLess = true
}
//Return Result
return isLess
}
func equalToDate(dateToCompare: NSDate) -> Bool {
//Declare Variables
var isEqualTo = false
//Compare Values
if self.compare(dateToCompare) == NSComparisonResult.OrderedSame {
isEqualTo = true
}
//Return Result
return isEqualTo
}
func addDays(daysToAdd: Int) -> NSDate {
let secondsInDays: NSTimeInterval = Double(daysToAdd) * 60 * 60 * 24
let dateWithDaysAdded: NSDate = self.dateByAddingTimeInterval(secondsInDays)
//Return Result
return dateWithDaysAdded
}
func addHours(hoursToAdd: Int) -> NSDate {
let secondsInHours: NSTimeInterval = Double(hoursToAdd) * 60 * 60
let dateWithHoursAdded: NSDate = self.dateByAddingTimeInterval(secondsInHours)
//Return Result
return dateWithHoursAdded
}
}
class ViewStoryModalViewController: UIViewController, PlayerDelegate {
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
var userFile = [PFFile]()
var createdAt = [NSDate]()
var objID = [String]()
var countInt = 0
@IBOutlet var imageView: UIImageView!
private var player: Player!
@IBOutlet var infoText: UILabel!
var imageArray: [UIImageView] = []
var videoArray: [Player] = []
var allArray: [AnyObject] = []
var allObjectID = [String]()
var percentInteractiveTransition: InteractiveTransition?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
modalPresentationStyle = .Custom
transitioningDelegate = self
percentInteractiveTransition = InteractiveTransition(attachedViewController: self)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var lastObjectID = NSUserDefaults().stringForKey("sisteObjIDKey")
var segueID = NSUserDefaults().integerForKey("segueID")
var myPlayer = Player()
override func viewDidLoad() {
super.viewDidLoad()
if (segueID == 10){ //10 = FULL STORY
print("Story")
queryStory()
}
if (segueID == 20){ //20 = RECENT
print("Recent")
queryStoryRecent()
}
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
imageView.addGestureRecognizer(tap)
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleHold))
imageView.addGestureRecognizer(longPressRecognizer)
imageView.userInteractionEnabled = true
imageView.hidden = true
infoText.hidden = false
imageView.layer.borderColor = UIColor.whiteColor().CGColor
imageView.layer.borderWidth = 1
myPlayer.delegate = self
myPlayer.view.frame.size.width = imageView.frame.size.width
myPlayer.view.frame.size.height = imageView.frame.size.height
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func downloadImages() {
if (countInt <= userFile.count - 1){
if ((userFile[countInt].url?.rangeOfString(".jpeg")) != nil){
var imageToInsert = UIImageView()
imageToInsert.frame.size = CGSizeMake(imageView.frame.size.width, imageView.frame.size.height)
imageToInsert.hnk_setImageFromURL(NSURL(string: userFile[countInt].url!)!)
countInt = countInt + 1
imageArray.insert(imageToInsert, atIndex: 0)
allArray.insert(imageToInsert, atIndex: 0)
allObjectID.insert(objID[countInt-1], atIndex: 0)
print("Image downloaded. Current image count: (imageArray.count)")
self.downloadImages()
}
if ((userFile[countInt].url?.rangeOfString(".mp4")) != nil){
let fileUrl = NSURL(string: userFile[countInt].url!)
var videoToInsert = Player()
videoToInsert.delegate = self
videoToInsert.view.frame.size.width = imageView.frame.size.width
videoToInsert.view.frame.size.height = imageView.frame.size.height
let videoUrl: NSURL = fileUrl!
videoToInsert.setUrl(videoUrl)
countInt = countInt + 1
videoArray.insert(videoToInsert, atIndex: 0)
allArray.insert(videoToInsert, atIndex: 0)
allObjectID.insert(objID[countInt-1], atIndex: 0)
print("Video downloaded. Current video count: (videoArray.count)")
self.downloadImages()
}
}
else{
print("no more items")
countInt = 0
delay(0.5){
self.infoText.text = "Trykk for å vise story"
self.imageView.hidden = false
}
}
}
func handleTapVideo(gestureRecognizer: UIGestureRecognizer)
{
if let viewWithTag = self.view.viewWithTag(999) {
print("Tag 999")
viewWithTag.removeFromSuperview()
handleTapFunc()
}
else {
print("tag not found")
}
}
func handleTap(gestureRecognizer: UIGestureRecognizer)
{
handleTapFunc()
}
func handleTapFunc() {
if (countInt <= allArray.count - 1){
if let object = allArray[countInt] as? UIImageView {
infoText.hidden = true
imageView.image = nil
print("set new image: (countInt)")
imageView.image = object.image
print(object.description)
print("ObjectID: (allObjectID[countInt])")
lastObjectID = allObjectID[countInt]
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(lastObjectID, forKey: "sisteObjIDKey")
defaults.synchronize()
}
if let object = allArray[countInt] as? Player {
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTapVideo))
object.view.addGestureRecognizer(tap)
object.view.tag = 999
print("set new video: (countInt)")
object.view.layer.borderColor = UIColor.whiteColor().CGColor
object.view.layer.borderWidth = 1
self.view.addSubview(object.view)
print(object.description)
print("ObjectID: (allObjectID[countInt])")
lastObjectID = allObjectID[countInt]
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(lastObjectID, forKey: "sisteObjIDKey")
defaults.synchronize()
object.playFromBeginning()
}
countInt = countInt + 1
}
else{
print("handleTap: no more items")
self.dismissViewControllerAnimated(true, completion: nil)
}
}
func queryStory(){
self.userFile.removeAll()
self.objID.removeAll()
self.createdAt.removeAll()
let query = PFQuery(className: "MyStory")
query.whereKey("isPending", equalTo: false)
query.limit = 1000
/*let date: NSDate = NSDate(timeIntervalSinceNow: -86400)// = 24 hours
query.whereKey("createdAt", greaterThan: date)*/
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (posts: [PFObject]?, error: NSError?) -> Void in
if (error == nil){
// Success fetching objects
print("Post count:", posts!.count)
for post in posts! {
if let imagefile = post["userFile"] as? PFFile {
self.userFile.append(post["userFile"] as! PFFile)
self.objID.append(post.objectId!)
self.createdAt.append(post.createdAt!)
}
}
self.downloadImages()
print("Uploaded files count: ", self.userFile.count)
}
else{
print(error)
let alert = UIAlertView()
alert.title = "Error"
alert.message = error?.localizedDescription
alert.addButtonWithTitle("OK")
alert.show()
}
}
}
func queryStoryRecent(){
self.userFile.removeAll()
self.objID.removeAll()
self.createdAt.removeAll()
let query = PFQuery(className: "MyStory")
query.whereKey("isPending", equalTo: false)
query.limit = 1000
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (posts: [PFObject]?, error: NSError?) -> Void in
if (error == nil){
// Success fetching objects
var thePostTime = NSDate()
for post in posts! {
if post.objectId == self.lastObjectID {
thePostTime = post.createdAt!
}
}
for post in posts! {
if post.createdAt!.isGreaterThanDate(thePostTime) == true {
if let imagefile = post["userFile"] as? PFFile {
self.userFile.append(post["userFile"] as! PFFile)
self.objID.append(post.objectId!)
self.createdAt.append(post.createdAt!)
}
}
}
self.downloadImages()
print("Done!")
}
else{
print(error)
}
}
}
// MARK: PlayerDelegate
func playerReady(player: Player) {
}
func playerPlaybackStateDidChange(player: Player) {
}
func playerBufferingStateDidChange(player: Player) {
}
func playerPlaybackWillStartFromBeginning(player: Player) {
}
func playerPlaybackDidEnd(player: Player) {
print("Video did end")
if let viewWithTag = self.view.viewWithTag(999) {
print("Tag 999")
viewWithTag.removeFromSuperview()
handleTapFunc()
}
else {
print("tag not found")
}
}
Please, if anyone has any tips that could help me make this more stable or other tips, tell me. Thanks in advanced :)
Aucun commentaire:
Enregistrer un commentaire