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://www.swiftdevcenter.com/save-and-get-objects-using-nskeyedarchiver-and-nskeyedunarchiver-swift-5/

 

Swift Development Center NSKeyedArchiver and NSKeyedUnarchive

Saving object using NSKeyedArchiver and NSKeyedUnarchive in the disc. Adding UIViewController extension will make it super easy.

www.swiftdevcenter.com

https://medium.com/@CoreyWDavis/reading-writing-and-deleting-files-in-swift-197e886416b0

 

Reading, Writing, and Deleting Files in Swift

Most of today’s average apps communicate via HTTP. While we can read and write data this way, it is still very common to need to save data…

medium.com

 

비동기 처리를 위한 OperationQueue

안드로이드의 AsyncTask 처럼 무거운 작업을 쓰레드로 돌리면서 메인 쓰레드는 그대로 동작하도록 구현할 때 필요하다

OperationQueue().addOperation {
            OperationQueue.main.addOperation {
            	//UI 작업
            }
            
            //백그라운드 작업
}

https://etst.tistory.com/114

 

[ iOS 앱 개발 - Swift] 비동기 프로그래밍과 OperationQueue

[ iOS 앱 개발 - Swift] 비동기 프로그래밍과 OperationQueue 이번에는 비동기 프로그래밍에 대해 공부를 해봤습니다! 느낀 바를 토대로 간단히 요약하자면, "여러명이 병렬적으로 일하게 만들기" 라고 �

etst.tistory.com

 

배경이 투명한 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.
}

https://www.it-swarm.dev/ko/swift/%eb%aa%a8%eb%8b%ac-%ed%91%9c%ec%8b%9c-%eb%b7%b0-%ec%bb%a8%ed%8a%b8%eb%a1%a4%eb%9f%ac%ec%9d%98-%ed%88%ac%eb%aa%85%ed%95%9c-%eb%b0%b0%ea%b2%bd/1049818603/

 

swift — 모달 표시 뷰 컨트롤러의 투명한 배경

누군가가 여전히 투명한 배경으로 어려움을 겪고있는 경우 언젠가이 솔루션을 발견했습니다. 어디를 기억할 수는 없지만 최신 Xcode & Swift에서는 여전히 잘 작동합니다. ContactListViewController2: UIVie

www.it-swarm.dev

 

효과음 재생하기

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)
        }
    }

https://robatokim.tistory.com/entry/SWIFT-AudioServicesPlaySystemSound%EC%9C%BC%EB%A1%9C-%ED%9A%A8%EA%B3%BC%EC%9D%8C-%EC%9E%AC%EC%83%9D%ED%95%98%EA%B8%B0

 

[SWIFT] AudioServicesPlaySystemSound으로 효과음 재생하기

프로그램을 만들다보면 효과음이나 음악 재생은 필수라고 할수 있다. 왜냐하면, 피드백 즉 유저 경험이 중요하기때문이다. 만약 화면 이동 버튼을 눌렀을때를 가정해보자. 터치나 클릭을 하면 �

robatokim.tistory.com

 

다중 배열 사용

이 부분은 기대보다 사용이 불편하다.

// 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

 

How do you create multi-dimensional arrays? - free Swift 5.1 example code and tips

Was this page useful? Let us know! 1 2 3 4 5

www.hackingwithswift.com

 

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

 

Delegate Method to UItableViewCell Swift

I have a Social Network Feed in form UItableView which has a cell. Now each cell has an image that animates when an even is triggered. Now, This event is in form of a string, will be triggered at e...

stackoverflow.com