创建单独的swift文件以处理我需要在整个应用程序中使用的功能的最佳方法是什么

时间:2018-07-21 11:06:38

标签: ios swift

我有一些ViewControllers,它们本质上是显示API中数据的模板。随着我继续开发,每个模板变得越来越混乱,我想对其进行清理,并在单独的文件中包含API函数,动画等,以便使模板ViewControllers井井有条。

我对任何一种编码都是陌生的,并且完成了一门课程并尝试边做边学。

这是我的模板之一的代码,它从api中获取加密货币数据,并根据用户选择的硬币显示数据,我有多个这样的模板,以便用户可以在每个页面上都有一个Coin 。最好创建单独的文件来管理动画,API数据等,这样我就可以在模板中调用它们并使其更加整洁,如果是的话,最好的方法是什么?谢谢。

//
//  Template2ViewController.swift
//  CryptoClockTesting
//
//  Created by Peter Ruppert on 18/07/2018.
//  Copyright © 2018 Peter Ruppert. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

var t2ViewController = Template2ViewController()

class Template2ViewController: UIViewController {

@IBOutlet weak var searchView: UIView!

var nameReady = Int()
var chosenCoin: String = ""
var symbolReady = Int()


//random background generate number
let b = Int(arc4random_uniform(6))
//choice appending the number of chosen coin from StartViewController
var choice = Int()
//Arrays for names and prices
var ids: [String] = []
var prices: [String] = []
var euros: [String] = []
var usd: [String] = []
var images: [String] = []
var names: [String] = []
//selection of random Background options
var backgroundArray = [ "Background0", "Background1", "Background2", "background3", "Background4", "Background5" ]
//labels and inputs
@IBOutlet weak var euroPrice: UILabel!
@IBOutlet weak var usdPrice: UILabel!
@IBOutlet weak var showConverter: UIButton!
@IBOutlet weak var newsView: UIView!
@IBOutlet weak var convertButton: UIButton!
@IBOutlet weak var textInput: UITextField!
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var labelName: UILabel!
@IBOutlet weak var currencyPrice: UILabel!
@IBOutlet weak var currencyIcon: UIImageView!

//Converting price from coin price to GBP
func convert() {
    let originalPrice = prices[choice]
    let priceAsDouble = Double(originalPrice)
    let chosenPrice = Double(round(1000*priceAsDouble!)/1000)
    let calculation = String(Double(textInput.text!)! / chosenPrice)
    let calcAsDouble = Double(calculation)
    let calcFinal = Double(round(1000*calcAsDouble!)/1000)
    if textInput.text != nil
    {
        textLabel.text = "\(calcFinal) \(names[choice])"
    }

}
//show/hide the converter
var showhide: Bool = false
@IBAction func showConverter(_ sender: Any) {
    if (showhide) {

        showhide = false
        self.tiOut(); self.tlOut(); self.cbOut()


    } else {

        showhide = true
        self.tlIn(); self.tiIn(); self.cbIn()

    }
}

//functions for showing and hiding each converter Item
func cbIn() {
    UIView.animate(withDuration: 0.5, delay: 0.0, options: [], animations: {
        self.convertButton.center.x -= self.view.bounds.width
    },
                   completion: nil
    )
}

func tiIn() {
    self.textInput.isHidden = false
    UIView.animate(withDuration: 0.5, delay: 0.0, options: [],
                   animations: {
                    self.textInput.center.x += self.view.bounds.width
    },
                   completion: nil
    )
}


func cbOut() {
    UIView.animate(withDuration: 0.5, delay: 0.0, options: [], animations: {
        self.convertButton.center.x += self.view.bounds.width
    },
                   completion: nil
    )
}

func tiOut() {
    UIView.animate(withDuration: 0.5, delay: 0.0, options: [],
                   animations: {
                    self.textInput.center.x -= self.view.bounds.width
    },
                   completion: nil
    )
}

func tlIn() {
    self.textLabel.isHidden = false
    UIView.animate(withDuration: 0.5, delay: 0.0, options: [],
                   animations: {
                    self.textLabel.center.x += self.view.bounds.width
    },
                   completion: nil
    )

}

func tlOut() {
    UIView.animate(withDuration: 0.5, delay: 0.0, options: [],
                   animations: {
                    self.textLabel.center.x -= self.view.bounds.width
    },
                   completion: nil
    )
}

//Convert button calls convert function
@IBAction func convertButton(_ sender: Any) {
    self.convert()
}

//page load animation, var appeared making sure animation only occurs once

func mainAnimations() {
    if appeared == false {
        UIView.animate(withDuration: 0.5, delay: 0.0, options: [], animations: {
            self.currencyIcon.center.y += self.view.bounds.height
        },
                       completion: nil
        )

        UIView.animate(withDuration: 0.5, delay: 0.3, options: [],
                       animations: {
                        self.currencyPrice.center.x += self.view.bounds.width
        },
                       completion: nil
        )

        UIView.animate(withDuration: 0.5, delay: 0.4, options: [],
                       animations: {
                        self.labelName.center.x -= self.view.bounds.width
        },
                       completion: nil
        )

        UIView.animate(withDuration: 0.8, delay: 2.0, options: [], animations: {

            self.euroPrice.alpha = 0.5
            self.usdPrice.alpha = 0.5
        })

        appeared = true

    } else {

    }
}

func backupAnimations() {
    UIView.animate(withDuration: 0.5, delay: 0.0, options: [], animations: {
        self.currencyIcon.center.y += self.view.bounds.height
    },
                   completion: nil
    )

    UIView.animate(withDuration: 0.5, delay: 0.3, options: [],
                   animations: {
                    self.currencyPrice.center.x += self.view.bounds.width
    },
                   completion: nil
    )

    UIView.animate(withDuration: 0.5, delay: 0.4, options: [],
                   animations: {
                    self.labelName.center.x -= self.view.bounds.width
    },
                   completion: nil
    )
}

var appeared: Bool = false
override func viewDidAppear(_ animated: Bool) {
    self.mainAnimations()

}



//Dismiss Keyboard when Tap
override func touchesBegan(_ touches: Set<UITouch>,
                           with event: UIEvent?) {
    self.view.endEditing(true)
}

//get permCoin from user defaults and generate number, so now on always will be this coin.
func getPermCoinNumber() {

    let permString = UserDefaults.standard.string(forKey: "temp2")!
    let permNumber = names.firstIndex(of: permString)

    choice = permNumber!

    print("Debugging")
    print(names.debugDescription)
    print(permString.debugDescription)
    print(permNumber.debugDescription)
    print("Debugging end")
}

func animateContainerOut() {
    UIView.animate(withDuration: 0.5, delay: 0.0, options: [], animations: {
        self.searchView.center.y += self.view.bounds.height
    },
                   completion: nil
    )
}
func hideContainerView(){

    animateContainerOut()
   appeared = false
    self.viewDidLoad()
    self.viewDidAppear(true)
    backupAnimations()
    NewPageSearch.tempCase = ""
    NewPageSearch.tempController = nil

}

//displays chosen currency
func chooseCurrency() {
    let chosenName = names[choice]
    labelName.text = chosenName

}

//displays chosen price
func choosePrice() {

    let usdsPrice = usd[choice]
    let usdDoule = Double(usdsPrice)
    let usdFinal = Double(round(1000*usdDoule!)/1000)

    let eurosPrice = euros[choice]
    let euroDouble = Double(eurosPrice)
    let euroFinal = Double(round(1000*euroDouble!)/1000)

    let originalPrice = prices[choice]
    let priceAsDouble = Double(originalPrice)
    let chosenPrice = Double(round(1000*priceAsDouble!)/1000)

    currencyPrice.text = "£\(chosenPrice)"
    euroPrice.text = "€\(euroFinal)"
    usdPrice.text = "$\(usdFinal)"

}

func chooseImage() {
    //displays chosen image
    let chosenImage = images[choice]

    let remoteImageUrl = URL(string: chosenImage)

    Alamofire.request(remoteImageUrl!).responseData { (response) in
        if response.error == nil {
            print(response.result)

            if let data = response.data {
                self.currencyIcon.image = UIImage(data: data)
            }
        }
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

   t2ViewController = self

    //choose random Background
    self.view.backgroundColor = UIColor( patternImage: UIImage(named: "\(backgroundArray[b])")!).withAlphaComponent(0.5)

    //Setup
    self.convertButton.center.x  += view.bounds.width
    self.textInput.center.x -= view.bounds.width
    self.textLabel.center.x -= view.bounds.width

    currencyIcon.center.y  -= view.bounds.height
    currencyPrice.center.x -= view.bounds.width
    labelName.center.x += view.bounds.width


    self.euroPrice.alpha = 0.0
    self.usdPrice.alpha = 0.0

    // Do any additional setup after loading the view.

    let urlString = "https://api.coingecko.com/api/v3/coins?per_page=300"

    if let url = URL(string: urlString) {
        if let data = try? String(contentsOf: url) {
            let json = JSON(parseJSON: data)


            parse(json: json)


        }

    }
}

//Parsing Coin API
func parse(json: JSON) {
    for result in json[].arrayValue {
        let name = result["name"].stringValue
        let price = result["market_data"]["current_price"]["gbp"].stringValue
        let euro = result["market_data"]["current_price"]["eur"].stringValue
        let usds = result["market_data"]["current_price"]["usd"].stringValue
        let image = result["image"]["small"].stringValue
        usd.append(usds)
        euros.append(euro)
        names.append(name)
        prices.append(price)
        images.append(image)
        }
    if (UserDefaults.standard.value(forKey: "temp2") as? String) == nil {
        //show firstsearch

        NewPageSearch.tempCase = "temp2"
        NewPageSearch.tempController = t2ViewController
        appeared = true
        self.searchView.isHidden = false
        print("T2VCDebug")
        print(NewPageSearch.tempCase)
        print(NewPageSearch.tempController)
    } else {
        //show main screen
        appeared = false
        self.searchView.isHidden = true
        self.getPermCoinNumber()
        self.chooseCurrency()
        self.choosePrice()
        self.chooseImage()
        NewPageSearch.tempCase = ""
        NewPageSearch.tempController = nil
    }



}



}

1 个答案:

答案 0 :(得分:0)

常见的是在应用程序中制作一个Network和Utility类来分别处理数据和UI,如

class Utility {

   static let shared = Utility()

   func animate(view:UIView) { // in your case you have same duration you can send only + or - or create 2 functions for each

  }
}

//

class Network {

   static let shared = Network()

   func getData(completion:@escaping(_arr:[Type])->()) { // in your case you have same duration you can send only + or - or create 2 functions for each
     /// alamofire / urlsession request
     /// after finish completion(arr) 
  }
}

//

您还可以进行这种共享

struct API {

   static let developmentUrlStr = "https://////"

   static let distributionUrlStr = "https://////"
}

//

Network.shared.getData { (arr) in 

   // get the array here 
}