Last active
September 5, 2017 07:57
-
-
Save asdwd5/31919950383f290709c5934853c3e9fc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// project | |
import UIKit | |
import Alamofire | |
import SwiftyJSON | |
import Haneke | |
class magazineViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, NSURLSessionDelegate, UIDocumentInteractionControllerDelegate, NSURLSessionTaskDelegate { | |
@IBOutlet weak var collectionView: UICollectionView! | |
@IBOutlet weak var progressLoading: UIActivityIndicatorView! | |
@IBOutlet weak var searchBar: UISearchBar! | |
var listMagazine = [String]() | |
var titleMagazine = [String]() | |
var imageMagazine = [String]() | |
var downloadDirectory: String = "" | |
var downloadTask: NSURLSessionDownloadTask! | |
var backgroundSession: NSURLSession! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
getData() | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { | |
return listMagazine.count | |
} | |
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { | |
let cell: magazineCell = self.collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! magazineCell | |
cell.progressDownload.hidden = true | |
cell.progressLabel.hidden = true | |
cell.progressDownload.setProgress(0, animated: true) | |
let imageUrl:NSURL = NSURL(string: imageMagazine[indexPath.row])! | |
cell.displayImage.hnk_setImageFromURL(imageUrl, placeholder: nil, success: { (image) -> Void in | |
cell.displayImage.image = image | |
cell.activityIndicator.hidden = true | |
cell.activityIndicator.stopAnimating() | |
//self.imagePlaceholder.hidden = true | |
}, failure: { (error) -> Void in | |
// when error | |
}) | |
cell.displayTitle.text = titleMagazine[indexPath.row] | |
return cell | |
} | |
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { | |
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! magazineCell | |
var localPath: NSURL? | |
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask) | |
Alamofire.download(.GET, listMagazine[indexPath.row], destination: { (temporaryURL, response) in | |
print("ITEM IS DOWNLOADING") | |
print(self.listMagazine[indexPath.item]) | |
let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] | |
let pathComponent = response.suggestedFilename | |
localPath = directoryURL.URLByAppendingPathComponent(pathComponent!) | |
return localPath! | |
}) | |
.response { (request, response, _, error) in | |
// print("this is response \(response)") | |
print("Downloaded file to \(localPath!)") | |
self.downloadDirectory = "\(localPath)" | |
} | |
let backgroundSessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("backgroundSession") | |
backgroundSession = NSURLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: NSOperationQueue.mainQueue()) | |
// var counter:Int = 0 { | |
// didSet { | |
// let fractionalProgress = Float(counter) / 100.0 | |
// let animated = counter != 0 | |
// | |
// print(counter) | |
// print("THE PROGRESS") | |
// | |
// cell.progressDownload.setProgress(fractionalProgress, animated: animated) | |
// cell.progressLabel.text = ("\(counter)%") | |
// } | |
// } | |
let url = NSURL(string: "\(localPath)")! | |
downloadTask = backgroundSession.downloadTaskWithURL(url) | |
downloadTask.resume() | |
cell.progressDownload.hidden = false | |
cell.progressLabel.hidden = false | |
print(localPath) | |
} | |
// func showFileWithPath(path: String){ | |
// let isFileFound:Bool? = NSFileManager.defaultManager().fileExistsAtPath(path) | |
// if isFileFound == true{ | |
// let viewer = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: path)) | |
// viewer.delegate = self | |
// viewer.presentPreviewAnimated(true) | |
// } | |
// } | |
// | |
// func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){ | |
// | |
// let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) | |
// let documentDirectoryPath:String = path[0] | |
// let fileManager = NSFileManager() | |
// let destinationURLForFile = NSURL(fileURLWithPath: documentDirectoryPath.stringByAppendingString("/file.pdf")) | |
// | |
// if fileManager.fileExistsAtPath(destinationURLForFile.path!){ | |
// showFileWithPath(destinationURLForFile.path!) | |
// } | |
// else{ | |
// do { | |
// try fileManager.moveItemAtURL(location, toURL: destinationURLForFile) | |
// // show file | |
// showFileWithPath(destinationURLForFile.path!) | |
// }catch{ | |
// print("An error occurred while moving file to destination url") | |
// } | |
// } | |
// } | |
// 2 | |
func URLSession(session: NSURLSession, | |
downloadTask: NSURLSessionDownloadTask, | |
didWriteData bytesWritten: Int64, | |
totalBytesWritten: Int64, | |
totalBytesExpectedToWrite: Int64, | |
cell: magazineCell){ | |
cell.progressDownload.setProgress(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite), animated: true) | |
} | |
func URLSession(session: NSURLSession, | |
task: NSURLSessionTask, | |
didCompleteWithError error: NSError?, | |
cell: magazineCell){ | |
downloadTask = nil | |
cell.progressDownload.setProgress(0.0, animated: true) | |
if (error != nil) { | |
print(error?.description) | |
}else{ | |
print("The task finished transferring data successfully") | |
} | |
} | |
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController{ | |
return self | |
} | |
func getData() { | |
self.progressLoading.startAnimating() | |
self.progressLoading.hidden = false | |
let config = Config() | |
let url = NSURL(string: config.BASE_URL + config.LIST_MAGAZINE + config.SecretKey())! | |
Alamofire.request(.GET, url).responseJSON { | |
(response) -> Void in | |
self.progressLoading.stopAnimating() | |
self.progressLoading.hidden = true | |
if response.result.isSuccess { | |
if let value = response.result.value { | |
let json = JSON(value) | |
let datas = json["items"].arrayValue | |
for data in datas { | |
self.listMagazine.append(data["magazine"].stringValue) | |
self.titleMagazine.append(data["title"].stringValue) | |
self.imageMagazine.append(data["image"].stringValue) | |
} | |
} | |
self.collectionView.reloadData() | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment