Can't Show images to iCarousel from web url - swift

I Want to Show some images from a website on iCarousel SlideShow.
I get Empty Slideshow from iCarousel.
I'm beginner and tried many codes by chance on my app but noting happened
Here is my Complete code :
import UIKit
class ViewController: UIViewController , iCarouselDataSource, iCarouselDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var allimages: UIImageView!
internal var urll:NSURL!
#IBOutlet weak var carouselView: iCarousel!
var numbers = [Int]()
var urls = [String]()
func carousel(carousel: iCarousel, viewForItemAtIndex index: Int, reusingView view: UIView?) -> UIView {
let tempView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
let images = UIButton(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
images.backgroundColor = UIColor.blueColor()
images.backgroundImageForState(.Normal)
images.backgroundRectForBounds(CGRect(x: 0, y: 0, width: 300, height: 200))
tempView.addSubview(images)
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
imageView.backgroundColor = UIColor.orangeColor()
for item in self.urls {
print (item)
let s = item
let url = NSURL(string: s)
let session = NSURLSession.sharedSession()
let task = session.downloadTaskWithURL(url!)
{
(url: NSURL?, res: NSURLResponse?, e: NSError?) in
let d = NSData(contentsOfURL: url!)
let image = UIImage(data: d!)
dispatch_async(dispatch_get_main_queue()) {
imageView.image = image
}
}
task.resume()
}
return images
}
func carousel(carousel: iCarousel, valueForOption option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
if option == iCarouselOption.Spacing {
return value * 1.1
}
return value
}
override func awakeFromNib() {
super.awakeFromNib()
numbers = [1,2,3,4]
}
func numberOfItemsInCarousel(carousel: iCarousel) -> Int {
return numbers.count
}
//==============================================================
override func viewDidLoad() {
carouselView.type = .Rotary
carouselView.autoscroll = 0.4
// let defaults = NSUserDefaults.standardUserDefaults()
urll = NSURL(string: "http://xxxxxxxxx.com/api/?slider=uij6sdnb")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(urll) {(NSData, response, error) -> Void in
do {
let records = try NSJSONSerialization.JSONObjectWithData(NSData!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
for record in records {
let urlid = Int(record["slide_id"] as! String)
let urimage = record["slide_url"] as! String
print(urlid)
print(urimage)
self.urls = [urimage]
// print(self.urls.count)
}
}
catch {
print("Json Error")
}
}
task.resume()
Any help will appreciated.

Here is my Complete Code.
But as you see its for 4 image.
For more or less images, you can apply the changes easily.
I added the icrousel from jared Davinson Youtube Channel.
Enjoy.
//
// ViewController.swift
// parniapharmed
//
// Created by Alfredo Uzumaki on 2016 AP.
// Copyright © 2016 AP Alfredo Uzumaki. All rights reserved.
//
import UIKit
import SystemConfiguration // for checking internet connection
class ViewController: UIViewController { // if you had any problem. command this line and uncommand the below line !
// class ViewController: UIViewController , iCarouselDataSource, iCarouselDelegate {
#IBOutlet weak var allimages: UIImageView!
internal var urll:NSURL!
#IBOutlet weak var carouselView: iCarousel!
#IBOutlet weak var img1: UIImageView!
#IBOutlet weak var img2: UIImageView!
#IBOutlet weak var img3: UIImageView!
#IBOutlet weak var img4: UIImageView!
#IBOutlet weak var allimagetop: UIView!
internal var imageNinja:String = ""
internal var hasInternet:Bool! // for checking internet connection
var numbers = [Int]()
var urls = [String]()
internal var urimage = [String]()
internal var image1:String = ""
internal var image2:String = ""
internal var image3:String = ""
internal var image4:String = ""
internal var imageArray: [UIImage] = []
func carousel(carousel: iCarousel, viewForItemAtIndex index: Int, reusingView view: UIView?) -> UIView {
var tempView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
let images = UIButton(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
images.backgroundColor = UIColor.blueColor()
images.backgroundImageForState(.Normal)
images.backgroundRectForBounds(CGRect(x: 0, y: 0, width: 300, height: 200))
tempView.addSubview(images)
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 400, height: 200))
imageView.image = UIImage(named: "loading")
if (imageNinja != "") && (imageArray.count == 4) { // Checking if images fully loaded you can Delete Seccond Condition if it Coused any Error
imageView.backgroundColor = UIColor.orangeColor()
imageView.image = imageArray[index]
tempView.addSubview(imageView)
}
return imageView
}
func carousel(carousel: iCarousel, valueForOption option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
if option == iCarouselOption.Spacing {
return value * 1.1
}
return value
}
override func awakeFromNib() {
super.awakeFromNib()
numbers = [1,2,3,4] // i wrote it manualy but you can change it to: numbers = imageArray.count or write the th numbers of your images.
}
func numberOfItemsInCarousel(carousel: iCarousel) -> Int {
return numbers.count
}
//===========================Begin of View Did Load===================================
override func viewDidLoad() {
carouselView.type = .Rotary
carouselView.autoscroll = 0.1
hasInternet = connectedToNetwork() //checking internet again !
print(hasInternet) // if true then internet is ok
if hasInternet == true {
urll = NSURL(string: "http://yourwebsite.com/api/?slider=uij6sdnb") // <== put your php address here !!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(urll) {(data, response, error) -> Void in
do {
let records = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
for record in records {
//slide_url is the subject of database row from php... change it to yours
let urimage = record["slide_url"] as! String
self.urls.append(urimage)
}
print(self.urls[2])
self.image1 = self.urls[0]
self.image2 = self.urls[1]
self.image3 = self.urls[2]
self.image4 = self.urls[3]
}
catch {
print("Json Error")
}
while self.imageNinja == "" {
self.image1 = self.urls[0]
self.image2 = self.urls[1]
self.image3 = self.urls[2]
self.image4 = self.urls[3]
print("4th image downloaded")
print(self.image4)
//----------------------------------- downoad image -----------------------------------------
let url = NSURL(string: self.image1)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let data = NSData(contentsOfURL: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check
dispatch_async(dispatch_get_main_queue(), {
let image = UIImage(data: data!)
self.imageArray.append(image!)
});
}
//----------------------------------- downoad image -----------------------------------------
//----------------------------------- downoad image -----------------------------------------
let url2 = NSURL(string: self.image2)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let data = NSData(contentsOfURL: url2!) //make sure your image in this url does exist, otherwise unwrap in a if let check
dispatch_async(dispatch_get_main_queue(), {
let image = UIImage(data: data!)
self.imageArray.append(image!)
});
}
//----------------------------------- downoad image -----------------------------------------
//----------------------------------- downoad image -----------------------------------------
let url3 = NSURL(string: self.image3)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let data = NSData(contentsOfURL: url3!) //make sure your image in this url does exist, otherwise unwrap in a if let check
dispatch_async(dispatch_get_main_queue(), {
let image = UIImage(data: data!)
self.imageArray.append(image!)
});
}
//----------------------------------- downoad image -----------------------------------------
//----------------------------------- downoad image -----------------------------------------
let url4 = NSURL(string: self.image4)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let data = NSData(contentsOfURL: url4!) //make sure your image in this url does exist, otherwise unwrap in a if let check
dispatch_async(dispatch_get_main_queue(), {
let image = UIImage(data: data!)
self.imageArray.append(image!)
print("imageArray Count is is :")
print(self.imageArray.count)
self.carouselView.reloadData() //this one is do nothing! i put it for luck!
});
}
//----------------------------------- downoad image -----------------------------------------
self.imageNinja = "hhh"
}
}
task.resume()
}
// ================================= end of view did load
}
// checking internet connection
func connectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else {
return false
}
var flags : SCNetworkReachabilityFlags = []
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == false {
return false
}
let isReachable = flags.contains(.Reachable)
let needsConnection = flags.contains(.ConnectionRequired)
return (isReachable && !needsConnection)
}
}

Related

How can i stop my frames from constantly being reloaded in swift

I have a code that detects objects and transcribes them to speech. However, if various objects are detected in the same frame the voice output gets messed up and starts saying the object's name all together making no sense to the user. I'm developing this application for the visually impaired so I'm trying to focus on getting an object's name transcribing it to the user and then move on to the next object.
Here is the code below.
import UIKit
import AVKit
import Vision
import CoreML
import AVFoundation
class ViewController: UIViewController , AVCaptureVideoDataOutputSampleBufferDelegate {
#IBOutlet weak var innerView: UIView!
#IBOutlet weak var viewLable: UILabel!
var previewLayer: AVCaptureVideoPreviewLayer?
override func viewDidLoad() {
super.viewDidLoad()
updateLable(newLable: "new lable")
//Start the Camera
let captureSession = AVCaptureSession()
captureSession.sessionPreset = .photo
// get back camera as Video Capture Device
guard let captureDevice = AVCaptureDevice.default(for: .video)
else { self.quickErr(myLine: #line,inputStr: "") ; return }
try? captureDevice.lockForConfiguration()
captureDevice.activeVideoMinFrameDuration = CMTimeMake(1, 2)
captureDevice.activeVideoMaxFrameDuration = CMTimeMake(1, 2)
captureDevice.unlockForConfiguration()
guard let input = try? AVCaptureDeviceInput(device: captureDevice)
else { self.quickErr(myLine: #line,inputStr: "") ; return }
captureSession.addInput(input)
captureSession.startRunning()
self.previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.previewLayer?.frame.size = self.innerView.frame.size
self.previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.innerView.layer.addSublayer(self.previewLayer!)
self.previewLayer?.frame = view.frame
// let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
// label.center = CGPoint(x: 160, y: 285)
// label.textAlignment = .center
// label.text = "I'am a test label"
// self.view.addSubview(label)
// label.text = ""
//get access to video frames
let dataOutput = AVCaptureVideoDataOutput()
dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "VideoQueue"))
captureSession.addOutput(dataOutput)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.previewLayer?.frame.size = self.innerView.frame.size
}
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
//print("Camera was able to capture a frame ", Date())
guard let pixcelBuffer:CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
else { self.quickErr(myLine: #line,inputStr: "") ; return }
guard let model = try? VNCoreMLModel(for: Resnet50().model)
else { self.quickErr(myLine: #line,inputStr: "") ; return }
let request = VNCoreMLRequest(model: model) { (finishedReq, err) in
//check err
//print(finishedReq.results)
guard let results = finishedReq.results as? [VNClassificationObservation]
else { self.quickErr(myLine: #line,inputStr: "") ; return }
guard let firstObservation = results.first
else { self.quickErr(myLine: #line,inputStr: "") ; return }
var myMessage = ""
var myConfident = 0
if (firstObservation.confidence > 0.2 ) {
myConfident = Int ( firstObservation.confidence * 100 )
let myIdentifier = firstObservation.identifier.split(separator: ",")
myMessage = "I am \(myConfident) % confidence this object is : \(myIdentifier[0]) "
} else {
myMessage = "I am not confidence to detect this object"
}
print(myMessage)
self.updateLable(newLable: myMessage)
if ( myConfident >= 70 ){
self.readyMe(myText: myMessage, myLang: "en_EN")
}
}
// Anaylize image
try? VNImageRequestHandler(cvPixelBuffer: pixcelBuffer, options: [:]).perform([request])
}
func readyMe(myText :String , myLang : String ) {
let uttrace = AVSpeechUtterance(string: myText )
uttrace.voice = AVSpeechSynthesisVoice(language: myLang)
uttrace.rate = 0.5
let synthesizer = AVSpeechSynthesizer()
synthesizer.speak(uttrace)
}
func quickErr(myLine: Int , inputStr : String = "" ) {
print("===> Guard Error \(inputStr) :\n    file:\(#file)\n    line:\(myLine)\n    function:\(#function) ")
}
func updateLable(newLable: String){
DispatchQueue.main.async { // Correct
self.viewLable?.text = "[ " + newLable + " ]"
}
}
}

How to solve error due to CIFilter on macOS app

I'm new in macOS App but A already done an iOS app.
I'll try to convert an image in grayscale
Compilation is ok, but i have this running error at "filter.outputImage"
The errror is : Thread 1: "-[NSImage imageByColorMatchingWorkingSpaceToColorSpace:]: unrecognized selector sent to instance 0x60000201e4e0"
what's wrong ?
import Cocoa
import AppKit
class ViewController: NSViewController {
#IBOutlet weak var Load: NSButton!
#IBOutlet weak var ImageSource: NSImageView!
#IBOutlet weak var ImageNG: NSImageView!
func grayscale(image: NSImage) -> NSImage? {
let width = image.size.width
let height = image.size.height
let cgsize = CGSize (width: width, height: height)
let context = CIContext(options: nil)
if let filter = CIFilter(name: "CIPhotoEffectMono") { //CIPhotoEffectNoir CIPhotoEffectMono CIPhotoEffectTonal CIPixellate
filter.setValue(image, forKey: kCIInputImageKey)
if let output = filter.outputImage {
if let cgImage = context.createCGImage(output, from: output.extent) {
return NSImage(cgImage : cgImage, size: cgsize)
}
}
}
return nil
}
#IBAction func LoadButtonClicked(_ sender: Any) {
ImageSource.image = NSImage(named:"IMAGE")
let imageNG = grayscale(image: ImageSource.image! )
ImageNG.image = imageNG
}
override func viewDidLoad() {
super.viewDidLoad()
}
override var representedObject: Any? {
didSet {
}
}
}
The value for kCIInputImageKey is a CIImage object, not an NSImage:
https://developer.apple.com/documentation/coreimage/kciinputimagekey.
Perhaps something like this:
if let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) {
filter.setValue(CIImage(cgImage: cgImage), forKey: kCIInputImageKey)
}

Swift - Visionkit How to edit the color of the buttons "Keep Scan" and "Retake"

I have a problem.
I've implemented the visionkit framework in order to detect a text when the camera is used.
The problem is that the colors of the buttons: "Keep Scan" and "Retake" are blue. I want them in black color. How can I fix this problem? I paste my code.
Thank you in advance!
import UIKit
import Vision
import VisionKit
class ScanText: UIViewController, VNDocumentCameraViewControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var TextScan: UITextView!
#IBOutlet weak var buttonStartShape: UIButton!
#IBOutlet weak var infoScattaUnaFoto: UILabel!
#IBOutlet weak var copyButtonShape: UIButton!
var textRecognitionRequest = VNRecognizeTextRequest(completionHandler: nil)
private let textRecognitionWorkQueue = DispatchQueue(label: "MyVisionScannerQueue", qos: .userInitiated, attributes: [], autoreleaseFrequency: .workItem)
var classView = ViewController()
var arrayText = String()
override func viewDidLoad() {
super.viewDidLoad()
imageView.layer.cornerRadius = 15
imageView.clipsToBounds = true
TextScan.layer.cornerRadius = 15
TextScan.clipsToBounds = true
copyButtonShape.layer.cornerRadius = 25
copyButtonShape.clipsToBounds = true
buttonStartShape.layer.cornerRadius = 25
buttonStartShape.clipsToBounds = true
TextScan.isEditable = true
setupVision()
}
#IBAction func TakePicture(_ sender: Any) {
let scannerViewController = VNDocumentCameraViewController()
scannerViewController.delegate = self
present(scannerViewController, animated: true)
}
private func setupVision() {
textRecognitionRequest = VNRecognizeTextRequest { (request, error) in
guard let observations = request.results as? [VNRecognizedTextObservation] else { return }
var detectedText = ""
for observation in observations {
guard let topCandidate = observation.topCandidates(2).first else { return }
print("text \(topCandidate.string) has confidence \(topCandidate.confidence)")
detectedText += topCandidate.string
detectedText += "\n"
}
DispatchQueue.main.async {
self.TextScan.isHidden = false
self.infoScattaUnaFoto.isHidden = true
self.copyButtonShape.isHidden = false
self.buttonStartShape.setTitle("Ripeti", for: .normal)
self.TextScan.text += detectedText
self.TextScan.flashScrollIndicators()
}
}
textRecognitionRequest.recognitionLevel = .accurate
}
private func processImage(_ image: UIImage) {
imageView.image = image
recognizeTextInImage(image)
}
private func recognizeTextInImage(_ image: UIImage) {
guard let cgImage = image.cgImage else { return }
TextScan.text = ""
textRecognitionWorkQueue.async {
let requestHandler = VNImageRequestHandler(cgImage: cgImage, options: [:])
do {
try requestHandler.perform([self.textRecognitionRequest])
} catch {
print(error)
}
}
}
func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) {
/* guard scan.pageCount >= 1 else {
controller.dismiss(animated: true)
return
}*/
for i in 0 ..< scan.pageCount {
let img = scan.imageOfPage(at: i)
processImage(img)
}
let originalImage = scan.imageOfPage(at: 0)
print(originalImage)
//let newImage = compressedImage(originalImage)
controller.dismiss(animated: true)
}
func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFailWithError error: Error) {
print(error)
controller.dismiss(animated: true)
}
func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) {
controller.dismiss(animated: true)
}
func compressedImage(_ originalImage: UIImage) -> UIImage {
guard let imageData = originalImage.jpegData(compressionQuality: 1),
let reloadedImage = UIImage(data: imageData) else {
return originalImage
}
return reloadedImage
}
//MARK: By tapping on this button, I pass all the data.
#IBAction func CopyText(_ sender: Any) {
let vc = (storyboard?.instantiateViewController(identifier: "SpeakDetail") as? ViewController)!
vc.textscannerized = TextScan.text
self.navigationController?.pushViewController(vc, animated: true)
}
}
You can try something like this:
scannerViewController.view.tintColor = .red

I'm getting the error "unrecognized selector sent to instance"

When I try to press on any button on my calculator it gives me the error unrecognized selector sent to instance 0x7f7f85e04e40 I updated this code from Swift 2 to Swift 4 but back then it used to work. What's wrong with the code?
import UIKit
class Valuta: UIViewController {
#IBOutlet weak var euro: UILabel!
#IBOutlet weak var zloty: UILabel!
#IBOutlet weak var topButton: UIButton!
#IBOutlet weak var bottomButton: UIButton!
var valutas : [ValutaWaarde] = []
var number = 0;
var isTypingNumber = false
var currentNumber = 0;
var currency = "PLN";
#IBAction func numberTapped(sender: AnyObject) {
let number = sender.currentTitle!
var disable = false
if number == "."{
if euro.text!.range(of: ".") != nil{
disable = true
}
}
if(disable == false){
if isTypingNumber {
euro.text = euro.text!+number!
} else {
euro.text = number
isTypingNumber = true
}
var output : Float;
if(currency == "EUR"){
output = (euro.text! as NSString).floatValue*Float((valutas[0].rates?.pLN!)!)
}
else{
output = (euro.text! as NSString).floatValue/Float((valutas[0].rates?.pLN!)!)
}
zloty.text = String(format: "%.2f", output)
}
}
#IBAction func resetCalculator(sender: AnyObject) {
isTypingNumber = false;
zloty.text = "0";
euro.text = "0";
}
override func viewDidLoad() {
super.viewDidLoad()
UINavigationBar.appearance().isTranslucent = false;
UINavigationBar.appearance().barTintColor = UIColor(red: CGFloat(51/255.0), green: 51/255, blue: 51/255, alpha: 1)
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white]
//Get list
let url = URL(string: "https://api.fixer.io/latest?symbols=PLN&base=EUR")
var request = NSMutableURLRequest(url: url! as URL, cachePolicy: NSURLRequest.CachePolicy.returnCacheDataElseLoad, timeoutInterval: Double.infinity)
if Reachability.isConnectedToNetwork(){
request = NSMutableURLRequest(url: url! as URL, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: Double.infinity);
}
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest,
completionHandler: { data, response, error -> Void in
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [[String: String]] {
for valutaData in json {
let valuta = ValutaWaarde(dictionary: valutaData as NSDictionary)
self.valutas.append(valuta!)
}
}
} catch { print(error) }
})
task.resume()
}
...
}
Try to re-connect #IBOutlets and #IBActions in storyboard.

SCNNode and Firebase

I have 15 box and I add an image on each boxnode as first material. How can I load the images from Firebase and add an Image to each node. I already know how to load images from Firebase, I want to know the best way I can add an image on each 15 nodes, Thanks.
Here's the view controller:
class newsVC: UIViewController, presentVCProtocol {
#IBOutlet var scnView: SCNView!
var newsScene = NewsScene(create: true)
var screenSize: CGRect!
var screenWidth: CGFloat!
var screenHeight: CGFloat!
var posts = [ArtModel]()
var post: ArtModel!
var arts = [ArtModel]()
static var imageCache: NSCache<NSString, UIImage> = NSCache()
var type: String!
override func viewDidLoad() {
super.viewDidLoad()
let scnView = self.scnView!
let scene = newsScene
scnView.scene = scene
scnView.autoenablesDefaultLighting = true
scnView.backgroundColor = UIColor.white
DataService.ds.REF_USERS.child((FIRAuth.auth()?.currentUser?.uid)!).child("arts").observe(.value) { (snapshot: FIRDataSnapshot) in
self.posts = []
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshot {
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = ArtModel(key: key, artData: postDict)
self.posts.insert(post, at: 0)
}
}
}
}
}
func configureView(_ post: ArtModel, img: UIImage? = nil, imageView: FXImageView? = nil) {
self.post = post
if img != nil {
self.newsScene.setup(image: img!)
print("IMAGE:\(img)")
} else {
let ref = FIRStorage.storage().reference(forURL: post.imgUrl)
ref.data(withMaxSize: 2 * 1024 * 1024, completion: { (data, error) in
if error != nil {
print("JESS: Unable to download image from Firebase storage")
print("Unable to download image: \(error?.localizedDescription)")
} else {
print("JESS: Image downloaded from Firebase storage")
if let imgData = data {
if let img = UIImage(data: imgData) {
self.newsScene.setup(image: img)
print("IMAGE:\(img)")
ProfileVC.imageCache.setObject(img, forKey: post.imgUrl as NSString)
}
}
}
})
}
}
}
Here's the NewsScene:
import SceneKit
import CoreMotion
import FirebaseAuth
import FirebaseStorage
import FirebaseDatabase
class NewsScene: SCNScene {
var geometry = SCNBox()
var boxnode = SCNNode()
var art: ArtModel!
var artImage = UIImage()
var index = IndexPath()
var geo = SCNBox()
var cameranode = SCNNode()
convenience init(create: Bool) {
self.init()
setup(image: artImage)
}
func setup(image: UIImage) {
self.artImage = image
typealias BoxDims = (width: CGFloat, height: CGFloat,
length: CGFloat, chamferRadius: CGFloat)
let box1Dim = BoxDims(CGFloat(0.8), CGFloat(0.8), CGFloat(0.10), CGFloat(0.01))
let box2Dim = BoxDims(CGFloat(0.7), CGFloat(0.7), CGFloat(0.10), CGFloat(0.01))
let box3Dim = BoxDims(CGFloat(0.8), CGFloat(0.6), CGFloat(0.10), CGFloat(0.01))
let box4Dim = BoxDims(CGFloat(0.8), CGFloat(0.9), CGFloat(0.10), CGFloat(0.01))
let box5Dim = BoxDims(CGFloat(0.9), CGFloat(1.0), CGFloat(0.10), CGFloat(0.01))
let box6Dim = BoxDims(CGFloat(0.4), CGFloat(0.5), CGFloat(0.10), CGFloat(0.01))
let box7Dim = BoxDims(CGFloat(0.9), CGFloat(0.7), CGFloat(0.10), CGFloat(0.01))
let box8Dim = BoxDims(CGFloat(0.7), CGFloat(0.8), CGFloat(0.10), CGFloat(0.01))
let box9Dim = BoxDims(CGFloat(0.9), CGFloat(0.9), CGFloat(0.10), CGFloat(0.01))
let box10Dim = BoxDims(CGFloat(0.6), CGFloat(0.6), CGFloat(0.10), CGFloat(0.01))
let box11Dim = BoxDims(CGFloat(0.7), CGFloat(0.7), CGFloat(0.10), CGFloat(0.01))
let box12Dim = BoxDims(CGFloat(0.8), CGFloat(0.8), CGFloat(0.10), CGFloat(0.01))
let box13Dim = BoxDims(CGFloat(0.6), CGFloat(0.8), CGFloat(0.10), CGFloat(0.01))
let box14Dim = BoxDims(CGFloat(0.6), CGFloat(0.6), CGFloat(0.10), CGFloat(0.01))
let box15Dim = BoxDims(CGFloat(0.9), CGFloat(0.9), CGFloat(0.10), CGFloat(0.01))
let allBoxDims = [box1Dim, box2Dim, box3Dim, box4Dim, box5Dim, box6Dim, box7Dim, box8Dim,box9Dim,box10Dim,box11Dim,box12Dim,box13Dim,box14Dim,box15Dim ]
let offset: Int = 50
var boxCounter: Int = 0
for xIndex: Int in 0...2 {
for yIndex: Int in 0...4 {
// create a geometry
let boxDim = allBoxDims[boxCounter]
geo = SCNBox(width: boxDim.width, height: boxDim.height, length: boxDim.length, chamferRadius: boxDim.chamferRadius)
let material = SCNMaterial()
material.diffuse.contents = image
geo.firstMaterial = material
boxCounter = boxCounter + 1
boxnode = SCNNode(geometry: geo)
boxnode.position.x = Float(xIndex - offset)
boxnode.position.y = Float(yIndex - offset)
self.rootNode.addChildNode(boxnode)
}
}
}
func deviceDidMove(motion: CMDeviceMotion?, error: NSError?) {
if let motion = motion {
boxnode.orientation = motion.gaze(atOrientation: UIApplication.shared.statusBarOrientation)
if error != nil {
print("DEVICEDIDMOVE: \(error?.localizedDescription)")
}
}
}
}