Why can't I use write(toFile: ) property on a string? - properties

I'm following a tutorial that was written in some earlier version of Swift, that teaches me how to read/write a .txt file in Swift3. Xcode has been doing a good job so far of letting me know when I'm using old syntax, and changing it for me to the latest syntax. However, I'm coming across something that works in an older version of Swift, but not the current one.
class ViewController: UIViewController {
// MARK: Properties
#IBOutlet weak var monthToEditTextField: UITextField!
#IBOutlet weak var bedTimeTextField: UITextField!
#IBOutlet weak var wakeTimeTextField: UITextField!
#IBOutlet weak var theLabel: UILabel!
#IBAction func saveButton(_ sender: UIButton)
{
var theMonth = monthToEditTextField.text
var bedTime = bedTimeTextField.text
var wakeTime = wakeTimeTextField.text
var stringForTXTFile = "The user's info is: \(theMonth), \(bedTime), \(wakeTime)"
let fileManager = FileManager.default
if (!fileManager.fileExists(atPath: filePath))
{
var writeError: NSError?
let fileToBeWritten = stringForTXTFile.write(toFile: // This is where the problem is
}
}
When I type
stringForTXTFile.write
I get this error box
What do I need to do in order to use the "write" property?

Write to file doesn't return Bool anymore in Swift3. It throws, so just delete let fileToBeWritten = and use do try catch error handling. Any code that needs to be run if the operation was successful needs to be placed below that inside the do try curly brackets. You can also use guard to unwrap your textfield optional strings. Try like this:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var monthToEditTextField: UITextField!
#IBOutlet weak var bedTimeTextField: UITextField!
#IBOutlet weak var wakeTimeTextField: UITextField!
#IBOutlet weak var theLabel: UILabel!
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("textFile.txt")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func save(_ sender: UIButton) {
guard
let theMonth = monthToEditTextField.text,
let bedTime = bedTimeTextField.text,
let wakeTime = wakeTimeTextField.text
else { return }
let stringForTXTFile = "The user's info is: \(theMonth), \(bedTime), \(wakeTime)"
do {
try stringForTXTFile.write(toFile: fileURL.path, atomically: true, encoding: .utf8)
// place code to be executed here if write was successful
} catch {
print(error.localizedDescription)
}
}
#IBAction func load(_ sender: UIButton) {
do {
theLabel.text = try String(contentsOf: fileURL)
} catch {
print(error.localizedDescription)
}
}
}

Related

Avoid automatic video comercial when I launch a webPage using webkit

recently I created a News App for my personal News. I am using 2 Viewcontrollers one of them to show the list of news with the photo and the other to show the detail of the new in a detailViewController using webKit.
my problem is that every time a hit a news on the tableview and go to the detailViewController an ad video for the source page is show automatically and it's very annoying, some times a need to hit the close button more than 2 times to close it.
My question is if there any function to avoid those videos?
this is the code:
import UIKit
import WebKit
class DetailViewController: UIViewController {
var articleUrl:String?
#IBOutlet weak var spinner: UIActivityIndicatorView!
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
}
override func viewWillAppear(_ animated: Bool) {
//check that there is url
if articleUrl != nil {
//create url objet
let urlObject = URL(string: articleUrl!)
guard urlObject != nil else {
return
}
//create the urlRequest
let request = URLRequest(url: urlObject!)
//start spinner
spinner.alpha = 1
spinner.startAnimating()
webView.configuration.allowsInlineMediaPlayback = true
webView.configuration.mediaTypesRequiringUserActionForPlayback = .video
webView.pauseAllMediaPlayback()
webView.load(request)
}
}
}
extension DetailViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
spinner.stopAnimating()
spinner.alpha = 0
}
}

Swift 5 - why does my collectionview disappear when embedded in a stackview?

I am trying to make an Amazon clone. I am working on the products details page. basically you search, you click the tableviewcell for the item you want and you land on the details page. everything loads except for the collectionview which contains the images. when I remove the stackview everything loads fine but when I embed the view's contents into the stackview the collectionviewcell disappears. the cellForItemAt method doesn't even get called. I don't know why and I could really use some help.
edit: it seems the imageView in the collection cell css unwrapping as nil. I'm not sure why. I connected it to the cell from the storyboard. not sure why it's not working. I turned it into an optional cell.imagioView?.kf.setImage(with: imageUrl) but the collection view loads without the images inside. I finally get the horizontal scrollable action but the images don't load. I'm printing the url for the image when it comes into focus but it cannot be added to the cell. it seems the collection cell is loading but the image can't be added for some reason.
here's the view controller that is supposed to display it
class ProductViewController: UIViewController, UICollectionViewDelegate {
#IBOutlet var stackedView: UIStackView!
#IBOutlet weak var detailedView: UIView!
#IBOutlet var detailPageView: UIScrollView!
#IBOutlet var imagesCarouselCollection: UICollectionView!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var desc: UILabel!
#IBOutlet weak var features: UILabel!
#IBOutlet weak var price: UILabel!
#IBOutlet weak var starsLabel: UILabel!
#IBOutlet weak var noOfReviews: UILabel!
#IBOutlet weak var addToCartBtn: UIButton!
#IBOutlet weak var buyNowBtn: UIButton!
var searchedText: String = ""
var asinForSearch: String = ""
var resultsManager = ResultsManager()
var productDeets: Products?
var imagesArray = Array<String>()
override func viewDidLoad() {
super.viewDidLoad()
resultsManager.detailsDelegate = self
search()
self.setupUI()
loadingIndicator.isAnimating = true
imagesCarouselCollection.delegate = self
imagesCarouselCollection.dataSource = self
imagesCarouselCollection.register(ImageCarouselViewCell.self, forCellWithReuseIdentifier: "ImageCarouselCollectionCell")
imagesCarouselCollection.frame = imagesCarouselCollection.bounds
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.populatePage()
}
}
#IBAction func buyNow(_ sender: Any) {
}
#IBAction func addToCart(_ sender: Any) {
}
func search(){
resultsManager.getDetails(asinForSearch)
}
func createFeaturesLabels(featuresArray: [String]) -> String {
var newFeatureString = ""
for feature in featuresArray {
newFeatureString.append(feature + "\n")
}
return newFeatureString
}
func populatePage(){
if let productResults = self.productDeets {
self.titleLabel.text = productResults.title
self.desc.text = productResults.productDescription
self.imagesArray = productDeets!.images
self.features.text = createFeaturesLabels(featuresArray: productResults.featureBullets)
self.price.text = "$" + String(productResults.price.currentPrice)
self.starsLabel.text = productResults.reviews.rating
self.noOfReviews.text = String(productResults.reviews.totalReviews)
self.loadingIndicator.isAnimating = false
self.stackedView.isHidden = false
}
}
// MARK: - UI Setup for loading icon
private func setupUI() {
if #available(iOS 13.0, *) {
overrideUserInterfaceStyle = .light
}
self.stackedView.isHidden = true
self.detailPageView.backgroundColor = .white
self.detailPageView.addSubview(loadingIndicator)
NSLayoutConstraint.activate([
loadingIndicator.centerXAnchor
.constraint(equalTo: self.view.centerXAnchor),
loadingIndicator.centerYAnchor
.constraint(equalTo: self.view.centerYAnchor),
loadingIndicator.widthAnchor
.constraint(equalToConstant: 50),
loadingIndicator.heightAnchor
.constraint(equalTo: self.loadingIndicator.widthAnchor)
])
}
// MARK: - Properties
let loadingIndicator: ProgressView = {
let progress = ProgressView(colors: [.red, .systemGreen, .systemBlue], lineWidth: 5)
progress.translatesAutoresizingMaskIntoConstraints = false
return progress
}()
}
extension ProductViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width: CGFloat = imagesCarouselCollection.bounds.size.width
let height: CGFloat = imagesCarouselCollection.bounds.size.height
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCarouselCollectionCell", for: indexPath) as! ImageCarouselViewCell
let imageUrl = URL(string: imagesArray[indexPath.item])
cell.imagioView.kf.setImage(with: imageUrl)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(imagesArray.count)
return imagesArray.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
}
extension ProductViewController: ResultsDetailDelegate {
func updateDetails(_ resultsManager: ResultsManager, products: Products) {
self.productDeets = products
}
}
class ImageCarouselViewCell: UICollectionViewCell {
#IBOutlet weak var imagioView: UIImageView!
}
I found the problem - it was with the layout. It was just as I suspected, half code from tutorials that a wasn't deleted. ended up trying to declare the collectionview and its contents in the storyboard and programmatically. it was fixed by following the layout advice in this tutorial https://www.youtube.com/watch?v=eWGu3hcL3ww
and for anyone else facing this problem here's the updated code.
class ProductViewController: UIViewController, UICollectionViewDelegate {
#IBOutlet var stackedView: UIStackView!
#IBOutlet weak var detailedView: UIView!
#IBOutlet var detailPageView: UIScrollView!
#IBOutlet var imagesCarouselCollection: UICollectionView!
#IBOutlet weak var imagesCarouselCollectionHeight: NSLayoutConstraint!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var desc: UILabel!
#IBOutlet weak var features: UILabel!
#IBOutlet weak var price: UILabel!
#IBOutlet weak var starsLabel: UILabel!
#IBOutlet weak var noOfReviews: UILabel!
#IBOutlet weak var addToCartBtn: UIButton!
#IBOutlet weak var buyNowBtn: UIButton!
var searchedText: String = ""
var asinForSearch: String = ""
var resultsManager = ResultsManager()
var productDeets: Products?
var imagesArray = Array<String>()
override func viewDidLoad() {
super.viewDidLoad()
resultsManager.detailsDelegate = self
search()
self.setupUI()
loadingIndicator.isAnimating = true
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 349, height: 410)
imagesCarouselCollection.collectionViewLayout = layout
layout.scrollDirection = .horizontal
imagesCarouselCollection.register(ImageCollectionViewCell.nib(), forCellWithReuseIdentifier: ImageCollectionViewCell.identifier)
imagesCarouselCollection.frame = imagesCarouselCollection.bounds
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.imagesCarouselCollection.delegate = self
self.imagesCarouselCollection.dataSource = self
self.populatePage()
}
}
#IBAction func buyNow(_ sender: Any) {
}
#IBAction func addToCart(_ sender: Any) {
}
func search(){
resultsManager.getDetails(asinForSearch)
}
func createFeaturesLabels(featuresArray: [String]) -> String {
var newFeatureString = ""
for feature in featuresArray {
newFeatureString.append(feature + "\n")
}
return newFeatureString
}
func populatePage(){
if let productResults = self.productDeets {
self.titleLabel.text = productResults.title
self.desc.text = productResults.productDescription
self.imagesArray = productDeets!.images
self.features.text = createFeaturesLabels(featuresArray: productResults.featureBullets)
self.price.text = "$" + String(productResults.price.currentPrice)
self.starsLabel.text = productResults.reviews.rating + " out of 5 stars"
self.noOfReviews.text = String(productResults.reviews.totalReviews) + " reviews"
self.loadingIndicator.isAnimating = false
self.stackedView.isHidden = false
}
}
// MARK: - UI Setup for loading icon
private func setupUI() {
if #available(iOS 13.0, *) {
overrideUserInterfaceStyle = .light
}
self.stackedView.isHidden = true
self.detailPageView.backgroundColor = .white
self.detailPageView.addSubview(loadingIndicator)
NSLayoutConstraint.activate([
loadingIndicator.centerXAnchor
.constraint(equalTo: self.view.centerXAnchor),
loadingIndicator.centerYAnchor
.constraint(equalTo: self.view.centerYAnchor),
loadingIndicator.widthAnchor
.constraint(equalToConstant: 50),
loadingIndicator.heightAnchor
.constraint(equalTo: self.loadingIndicator.widthAnchor)
])
}
// MARK: - Properties
let loadingIndicator: ProgressView = {
let progress = ProgressView(colors: [.red, .systemGreen, .systemBlue], lineWidth: 5)
progress.translatesAutoresizingMaskIntoConstraints = false
return progress
}()
}
extension ProductViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageCollectionViewCell.identifier, for: indexPath) as! ImageCollectionViewCell
let imageUrl = URL(string: imagesArray[indexPath.item])
cell.configure(with: imageUrl!)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagesArray.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
}
extension ProductViewController: ResultsDetailDelegate {
func updateDetails(_ resultsManager: ResultsManager, products: Products) {
self.productDeets = products
}
}
I also moved away from just using a CocoaTouch class and created a new one with a xib/nib
class ImageCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var productImageView: UIImageView!
static let identifier = "ImageCollectionViewCell"
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
public func configure(with imageURL: URL) {
productImageView.kf.setImage(with: imageURL)
}
static func nib() -> UINib {
return UINib(nibName: "ImageCollectionViewCell", bundle: nil)
}
}

How to Play The NsData or CMSampleBuffer that i have in the method?

I am sending the nsdata over a UDP socket and want to play this over there so how can I play this? Am I sending the right data to play?
class ViewController: UIViewController,AVCaptureAudioDataOutputSampleBufferDelegate {
// Global Scope of Session
let session = AVCaptureSession()
#IBOutlet weak var recBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func recBtnAction(_ sender: Any) {
session.sessionPreset = .medium
let mic = AVCaptureDevice.default(for: .audio)
var mic_input: AVCaptureDeviceInput!
let audio_output = AVCaptureAudioDataOutput()
audio_output.setSampleBufferDelegate(self, queue: DispatchQueue.main)
do
{
if let temp = mic {
mic_input = try AVCaptureDeviceInput(device: temp)
}
}
catch
{
return
}
if session.inputs.isEmpty {
session.addInput(mic_input)
session.addOutput(audio_output)
}
session.startRunning()
}
#IBAction func StopBtnAction(_ sender: Any){
session.stopRunning()
}
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
let block = CMSampleBufferGetDataBuffer(sampleBuffer)
var length = 0
var data: UnsafeMutablePointer<Int8>? = nil
var status = CMBlockBufferGetDataPointer(block!, 0, nil, &length, &data) // TODO: check for errors
let result = NSData(bytesNoCopy: data!, length: length, freeWhenDone: false)
print("NSDATA")
print(result)
}
}
Above is the code which I used to hear the mic data and convert to nsdata and send but I can't play this nsdata so is this right approach to send mic audio data over a socket?

UIMenuItem #selector method crash in wkwebview

UIMenuItem selector method crashes in iOS 11 beta SDK.
-[WKContentView highlightText]: unrecognized selector sent to instance 0x7f85df8f3200
Method Definition:
func highlightText()
{
//
}
I try to add UIMenuItem in WKWebView,
let menuItemHighlight = UIMenuItem.init(title: "Highlight", action: #selector(ContentWebkitView.highlightText))
UIMenuController.shared.menuItems = [menuItemHighlight]
I was also getting this error when I was overriding canPerformAction and checking for my custom selector. In my case I wanted to remove all menu items except for my custom one and the following made this work for me.
class ViewController: UIViewController {
#IBOutlet weak var webView: MyWebView!
override func viewDidLoad() {
super.viewDidLoad()
loadWebView()
setupCustomMenu()
}
func loadWebView() {
let url = URL(string: "http://www.google.com")
let request = URLRequest(url: url!)
webView.load(request)
}
func setupCustomMenu() {
let customMenuItem = UIMenuItem(title: "Foo", action:
#selector(ViewController.customMenuTapped))
UIMenuController.shared.menuItems = [customMenuItem]
UIMenuController.shared.update()
}
#objc func customMenuTapped() {
let yay = "🤪🤪🤪🤪🤪🤪🤪🤪🤪🤪🤪🤪"
let alertView = UIAlertController(title: "Yay!!", message: yay, preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "cool", style: .default, handler: nil))
present(alertView, animated: true, completion: nil)
}
}
class MyWebView: WKWebView {
// turn off all other menu items
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
}
OK, we finally made it work for Swift 4:
In your WKWebView subclass, add the following property and method:
// MARK: - Swizzling to avoid responder chain crash
var wkContentView: UIView? {
return self.subviewWithClassName("WKContentView")
}
private func swizzleResponderChainAction() {
wkContentView?.swizzlePerformAction()
}
Then, add an extension to UIView (I put it in the same file as my WKWebView subclass, you can make it fileprivate if you'd like)
// MARK: - Extension used for the swizzling part linked to wkContentView
extension UIView {
/// Find a subview corresponding to the className parameter, recursively.
func subviewWithClassName(_ className: String) -> UIView? {
if NSStringFromClass(type(of: self)) == className {
return self
} else {
for subview in subviews {
return subview.subviewWithClassName(className)
}
}
return nil
}
func swizzlePerformAction() {
swizzleMethod(#selector(canPerformAction), withSelector: #selector(swizzledCanPerformAction))
}
private func swizzleMethod(_ currentSelector: Selector, withSelector newSelector: Selector) {
if let currentMethod = self.instanceMethod(for: currentSelector),
let newMethod = self.instanceMethod(for:newSelector) {
let newImplementation = method_getImplementation(newMethod)
method_setImplementation(currentMethod, newImplementation)
} else {
print("Could not find originalSelector")
}
}
private func instanceMethod(for selector: Selector) -> Method? {
let classType = type(of: self)
return class_getInstanceMethod(classType, selector)
}
#objc private func swizzledCanPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
}
Now the UIMenuItem works as expected:
But honestly, this really feels like a hack, and I would love Apple to fix this issue :-/
Thanks for Stephan Heilner for his answer: https://stackoverflow.com/a/42985441/4670400

How to pass variables from one View Controller to another in WatchOS 2 & Swift

I am having a lot of problems trying to get a couple of variables from one View Controller to the next. How can I do it properly?
Here's my code below. This is the view controller where I want to be able to send the variables RedScoreW and BlueScoreW to the next window. I am asking on HOW TO DO THIS using SWIFT language and specially for WATCHOS apps.
class InterfaceController2: WKInterfaceController {
var RedScoreW = 0
var BlueScoreW = 0
#IBOutlet var WatchRedScoreLabel: WKInterfaceLabel!
#IBOutlet var WatchBlueScoreLabel: WKInterfaceLabel!
#IBAction func RedScorePlus() {
if RedScoreW == 999 {
RedScoreW = 0
WatchRedScoreLabel.setText("0")
}else {
RedScoreW += 1
WatchRedScoreLabel.setText(String(RedScoreW))
}
}
#IBAction func RedScoreMinus() {
if RedScoreW == 0 {
RedScoreW = 999
WatchRedScoreLabel.setText("999")
}
else {
RedScoreW -= 1
WatchRedScoreLabel.setText(String(RedScoreW))
}
}
#IBAction func BlueScorePlus() {
if BlueScoreW == 999 {
BlueScoreW = 0
WatchBlueScoreLabel.setText("0")
} else{
BlueScoreW += 1
WatchBlueScoreLabel.setText(String(BlueScoreW))
}
}
#IBAction func BlueScoreMinus() {
if BlueScoreW == 0 {
BlueScoreW = 999
WatchBlueScoreLabel.setText("999")
}
else {
BlueScoreW -= 1
WatchBlueScoreLabel.setText(String(BlueScoreW))
}
}
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
WatchRedScoreLabel.setText(String(RedScoreW))
WatchBlueScoreLabel.setText(String(BlueScoreW))
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
And this is the Destination View Controller where I want to be able to use RedScoreW and BlueScoreW variables.
class InterfaceController3: WKInterfaceController {
#IBOutlet var finalRedScoreLabel: WKInterfaceLabel!
#IBOutlet var finalBlueScoreLabel: WKInterfaceLabel!
#IBAction func DoneAndResetButton() {
self.popToRootController()
}
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
* EDIT *
I am trying to do it this way, this is the code where I send it, check:
#IBAction func FinishButtonPushVariables() {
arrayofScores[0] = RedScoreW
arrayofScores[1] = BlueScoreW
pushControllerWithName("LastScreen", context: arrayofScores)
}
And this is where I receive it... and it doesn't work. LOL
#IBOutlet var finalRedScoreLabel: WKInterfaceLabel!
#IBOutlet var finalBlueScoreLabel: WKInterfaceLabel!
#IBAction func DoneAndResetButton() {
self.popToRootController()
}
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
let finalarrayofScores = context as? InterfaceController2
finalBlueScoreLabel.setText(String(finalarrayofScores!.arrayofScores[1]))
finalRedScoreLabel.setText(String(finalarrayofScores!.arrayofScores[0]))
// Configure interface objects here.
}
In iOS apps, we use prepareForSegue to do this. On watchOS apps, we use contextForSegueWithIdentifier to pass a context from one interfaceController to another.
Here is a link to the class reference that will detail more about this. But here are the basics:
There are two different methods that can be used. One is for going from one interface controller to another:
func contextForSegueWithIdentifier(_ segueIdentifier: String) -> AnyObject?
The other is for going from a one interface controller to another when a row in a table is tapped:
func contextForSegueWithIdentifier(_ segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex rowIndex: Int) -> AnyObject?
So one of these two methods will go in the interfaceController that is sending the context, and you will receive that context in the awakeWithContext method of the receiving interfaceController.
Here is a link to a tutorial that will show an application of this process.
EDIT
Here is a specific solution to your problem.
In the interface controller where you send it, put this code:
override func contextForSegueWithIdentifier(segueIdentifier: String) -> AnyObject? {
arrayofScores[0] = RedScoreW
arrayofScores[1] = BlueScoreW
return arrayOfScores
}
Then in your destination interface controller, put this code:
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
let finalArrayOfScores = context as? [Int]
if let f = finalArrayOfScores {
finalBlueScoreLabel.setText(String(f[1]))
finalRedScoreLabel.setText(String(f[0]))
}
}
You need to set up variables to hold your variable first.
class YourSecondViewController: UIViewController {
var yourVariable:Double?
}
Then have your button trigger your custom segue. Use your variable as the argument for sender.
class YourFirstViewController: UIViewController {
#IBAction func buttonTapped(sender: AnyObject) {
self.performSegueWithIdentifier("segue", sender: yourVariable)
}
}
Then pass the sender data by overriding the prepareForSegue method:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier = "segue") {
let secondViewController = segue.destinationViewController as YourSecondViewController
let yourVariable = sender as Double
secondViewController.duration = yourVariable
}
}
I guess your problem is that you are passing an array to the context and you cast it as WKIntefaceController.
Try replacing this line
let finalarrayofScores = context as? InterfaceController2
by
let finalarrayofScores = context as? [Int]