swift 保存csv

csv.swift
func createCSV(){
        guard let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH-dd-MM-yyyy"
        let date = dateFormatter.string(from: Date())
        
        //Naming the File
        var fileName = date + "__" + NSUUID().uuidString.lowercased()
        if phoneLocationInCar! == "Mount"{
            fileName = "mount__" + fileName
        }
        else{
            fileName = "unmount__" + fileName
        }
        
        let fileURL = documentDirectory.appendingPathComponent(fileName).appendingPathExtension("csv")
        print("File PAth: \(fileURL.path)")
        // creating Header of csv
        var csvText = "accelerationX,accelerationY,accelerationZ,gravityX,gravityY,gravityZ,rotationX,rotationY,rotationZ,attitudeYaw, attitudeRoll,attitudePitch,heading,magneticFieldX,magneticFieldY,magneticFieldZ,magneticFieldAccuracy,latitude,longitude,horizontalAccuracy,verticalAccuracy,floor,speed,locationTimestamp,course,altitude,timestamp,actionType,phoneLocationInCar,attitudeRotationMatrixM11,attitudeRotationMatrixM12,attitudeRotationMatrixM13,attitudeRotationMatrixM21,attitudeRotationMatrixM22,attitudeRotationMatrixM23,attitudeRotationMatrixM31,attitudeRotationMatrixM32,attitudeRotationMatrixM33,attitudeQuaternionW,attitudeQuaternionX,attitudeQuaternionY,attitudeQuaternionZ                \n"
        
        // Adding Data
        csvText += self.sensorData.toString() // it returns "row text comma seperated \n"
        
        do {
            try csvText.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
            /*let vc = UIActivityViewController(activityItems: [fileURL], applicationActivities: [])
             vc.excludedActivityTypes = [
             UIActivityType.assignToContact,
             UIActivityType.saveToCameraRoll,
             UIActivityType.postToFlickr,
             UIActivityType.postToVimeo,
             UIActivityType.postToTencentWeibo,
             UIActivityType.postToTwitter,
             UIActivityType.postToFacebook,
             UIActivityType.openInIBooks
             ]
             present(vc, animated: true, completion: nil)*/
            
        } catch {
            print("Failed to create file")
            print("\(error)")
        }
        
    }

swift 防止屏幕锁定应用

如果闲置无限时,手机将不会锁定

.swift
UIApplication.shared.isIdleTimerDisabled = true // add below line in AppDelegate.swift

swift 键盘秀

同时显示键盘的动画

.swift
1. RSKKeyboardAnimationObserver: Easy way to handle iOS keyboard showing/dismissing.
  Source: https://github.com/ruslanskorb/RSKKeyboardAnimationObserver
  
2. Also see example code in "Keyboard avoid" snippet

swift 键盘避免

显示通过滑动或更改视图在写入时由键盘弹出窗口切割的视图

pod.swift
1. IHKeyboardAvoiding: 
  import IHKeyboardAvoiding
  override func viewDidAppear(_ animated: Bool) {
        KeyboardAvoiding.avoidingView = self.view
    }
  Source: https://cocoapods.org/pods/IHKeyboardAvoiding

2. Search Keyboard avoid on https://cocoapods.org 
code.swift
	a. add  
class ChatViewController: UIViewController, UITextFieldDelegate
	a. add your class as delegate in viewDidLoad method
	messageTextfield.delegate = self as
	b. add your text field delegate methods
	height of keyboard : 258 points
	height of messageField = height of keyboard + height of your view
	//TODO: Declare textFieldDidBeginEditing here:
	    func textFieldDidBeginEditing(_ textField: UITextField) {
	        
	        UIView.animate(withDuration: 0.5) {
	            self.heightConstraint.constant = 308 //update height
	            self.view.layoutIfNeeded() // update the constraints of view and redraw it if needed
	        }
	        
	    }
	  
	    
	    // this below method is not automatically called as above method it needs to be called
	    //TODO: Declare textFieldDidEndEditing here:
	    func textFieldDidEndEditing(_ textField: UITextField) {
	        UIView.animate(withDuration: 0.5) {
	            self.heightConstraint.constant = 50 //update height
	            self.view.layoutIfNeeded() //update the constraints of view and redraw it if needed
	        }
	    }
	
	// call textFieldDidEndEditing method
		add the following in viewDidLoad method
			//TODO: Set the tapGesture here:
		        let tapGesture =  UITapGestureRecognizer(target: self, action: #selector(tableViewTapped))
		        // add tap gessture to table view
		        messageTableView.addGestureRecognizer(tapGesture)
		
		decalare this function
			func tableViewTapped(){
			        messageTextfield.endEditing(true)
    }

swift 键盘解雇

写完后关闭键盘

pod.swift

1. KeyboardDismisser:- is a little Swift 4.x pod that adds a button over keyboard so that users can dismiss keyboard easily.
   Source: https://cocoapods.org/pods/KeyboardDismisser
   
2. IQKeyboardManager:- good solution
   Source: https://cocoapods.org/pods/IQKeyboardManagerSwift
code.swift
// Source: https://stackoverflow.com/questions/24126678/close-ios-keyboard-by-touching-anywhere-using-swift

// 1. 
override func viewDidLoad() {
        super.viewDidLoad()
        
        //Looks for single or multiple taps.
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:  #selector(dismissKeyboard))
        
        //Uncomment the line below if you want the tap not not interfere and cancel other interactions.
        //tap.cancelsTouchesInView = false
        self.view.addGestureRecognizer(tap)
    }
    
//Calls this function when the tap is recognized.
@objc func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    self.view.endEditing(true)
}

// 2. Above website contains easy method of creating an extension of textfield for multiple view controllers
// https://stackoverflow.com/questions/24126678/close-ios-keyboard-by-touching-anywhere-using-swift

swift

来源:https://cocoapods.org/pods/Fabric

ex.swift
FABRIC
1. always turn the net on of your iphone/emulator so that fabric can connect to the servers
2. in build settings -> click all -> search dsym -> select dwarf with dsym
3. go to project navigator -> app -> Targets -> app -> on right hand side File Inspector -> identity and type ->change name of app
4. go to file -> workspace settings -> change build system to legacy.

swift 改变app的背景颜色

ex.swift
self.view.backgroundColor = UIColor.green

swift 在主线程上运行代码

来源:https://www.codevscolor.com/swift-4-run-a-piece-of-code-main-thread/

_.swift
DispatchQueue.main.async{
            self.tableView.reloadData()
}

swift 获取随机数

此函数将帮助您获得随机的true或false布尔值。

randomNumber.swift
func randomBool() -> Bool {
    return arc4random_uniform(2) == 0 ? true : false
}

swift UIView + Anchors(需要修改)

UIViewAnchors

import UIKit

extension UIView {
    
    func addSubviews(_ views: UIView...) {
        views.forEach { addSubview($0) }
    }
    
    public func fillSuperview() {
        translatesAutoresizingMaskIntoConstraints = false
        if let superview = superview {
            leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
            rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true
            topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
            bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
        }
    }
    
    public func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0, centerXInSuperView: Bool = false, centerYInSuperView: Bool = false) {
        translatesAutoresizingMaskIntoConstraints = false
        
        _ = anchorWithReturnAnchors(top, left: left, bottom: bottom, right: right, topConstant: topConstant, leftConstant: leftConstant, bottomConstant: bottomConstant, rightConstant: rightConstant, widthConstant: widthConstant, heightConstant: heightConstant)
        if centerXInSuperView {
            anchorCenterXToSuperview()
        }
        if centerYInSuperView {
            anchorCenterYToSuperview()
        }
    }
    
    public func anchorWithReturnAnchors(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
        translatesAutoresizingMaskIntoConstraints = false
        
        var anchors = [NSLayoutConstraint]()
        
        if let top = top {
            anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
        }
        
        if let left = left {
            anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
        }
        
        if let bottom = bottom {
            anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
        }
        
        if let right = right {
            anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
        }
        
        if widthConstant > 0 {
            anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
        }
        
        if heightConstant > 0 {
            anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
        }
        
        anchors.forEach({$0.isActive = true})
        
        return anchors
    }
    
    public func anchorCenterXToSuperview(constant: CGFloat = 0) {
        translatesAutoresizingMaskIntoConstraints = false
        if let anchor = superview?.centerXAnchor {
            centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
        }
    }
    
    public func anchorCenterYToSuperview(constant: CGFloat = 0) {
        translatesAutoresizingMaskIntoConstraints = false
        if let anchor = superview?.centerYAnchor {
            centerYAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
        }
    }
    
    public func anchorCenterSuperview(constantX: CGFloat = 0, constantY: CGFloat = 0) {
        anchorCenterXToSuperview(constant: constantX)
        anchorCenterYToSuperview(constant: constantY)
    }
}