Swift 개발 팁
2020. 8. 31. 15:31ㆍ아이폰 개발
커스텀 클래스 객체 파일 입출력
기본이 되는 중요한 기능 중에 하나인데 이렇게 쓸만한 레퍼런스가 없음에 놀랍다.
// Save object in document directory
func saveObject(fileName: String, object: Any) -> Bool {
let filePath = self.getDirectoryPath().appendingPathComponent(fileName)//1
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: false)//2
try data.write(to: filePath)//3
return true
} catch {
print("error is: \(error.localizedDescription)")//4
}
return false
}
// Get object from document directory
func getObject(fileName: String) -> Any? {
let filePath = self.getDirectoryPath().appendingPathComponent(fileName)//5
do {
let data = try Data(contentsOf: filePath)//6
let object = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)//7
return object//8
} catch {
print("error is: \(error.localizedDescription)")//9
}
return nil
}
//Get the document directory path
//10
func getDirectoryPath() -> URL {
let arrayPaths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return arrayPaths[0]
}
class Car: NSObject, NSCoding {
var brand: String?
var madel: String?
func encode(with aCoder: NSCoder) {
aCoder.encode(self.madel, forKey:"madel")
aCoder.encode(self.brand, forKey:"brand")
}
required init?(coder aDecoder: NSCoder) {
self.madel = aDecoder.decodeObject(forKey:"madel") as? String
self.brand = aDecoder.decodeObject(forKey:"brand") as? String
}
init(barand: String, model: String) {
self.brand = barand
self.madel = model
}
}
let car = Car(barand: "Audi", model: "A4")
if self.saveObject(fileName: "myCar", object: car) {
print("saved")
} else {
print("not saved")
}
// Get the saved Car object
if let car = self.getObject(fileName: "myCar") as? Car {
print("my car is: \(car)")
}
https://medium.com/@CoreyWDavis/reading-writing-and-deleting-files-in-swift-197e886416b0
비동기 처리를 위한 OperationQueue
안드로이드의 AsyncTask 처럼 무거운 작업을 쓰레드로 돌리면서 메인 쓰레드는 그대로 동작하도록 구현할 때 필요하다
OperationQueue().addOperation {
OperationQueue.main.addOperation {
//UI 작업
}
//백그라운드 작업
}
배경이 투명한 ViewController 실행
func presentModal() {
let modalController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
present(modalViewController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
view.isOpaque = false
view.backgroundColor = .clear // try other colors, say: .white or black with Alpha etc.
}
효과음 재생하기
import AudioToolbox
func playSound(filename:String, ext:String) {
if let soundUrl = Bundle.main.url(forResource: filename, withExtension: ext) {
var soundId:SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundUrl as CFURL, &soundId)
AudioServicesAddSystemSoundCompletion(soundId, nil, nil, { (soundId, clientData) -> Void in
AudioServicesDisposeSystemSoundID(soundId)
}, nil)
AudioServicesPlaySystemSound(soundId)
}
}
다중 배열 사용
이 부분은 기대보다 사용이 불편하다.
// this is our array of arrays
var groups = [[String]]()
// we create three simple string arrays for testing
var groupA = ["England", "Ireland", "Scotland", "Wales"]
var groupB = ["Canada", "Mexico", "United States"]
var groupC = ["China", "Japan", "South Korea"]
// then add them all to the "groups" array
groups.append(groupA)
groups.append(groupB)
groups.append(groupC)
// this will print out the array of arays
print("The groups are:", groups)
// we now append an item to one of the arrays
groups[1].append("Costa Rica")
print("\nAfter adding Costa Rica, the groups are:", groups)
// and now print out groupB's contents again
print("\nGroup B still contains:", groupB)
https://www.hackingwithswift.com/example-code/arrays/how-do-you-create-multi-dimensional-arrays
ListItemViewCell에서 delegation 처리
매번 까먹어서 쓸때마다 찾아봐야하는...
protocol CustomCellDelegate: class {
func animationStarted()
func animationFinished()
}
class CustomCell: UITableViewCell {
// Don't unwrap in case the cell is enqueued!
weak var delegate: CustomCellDelegate?
/* Some initialization of the cell */
func performAnimation() {
delegate?.animationStarted()
UIView.animate(withDuration: 0.5, animations: {
/* Do some cool animation */
}) { finished in
self.delegate?.animationFinished()
}
}
}
https://stackoverflow.com/questions/47079135/delegate-method-to-uitableviewcell-swift