9 Notes in August Swift 4.2
1. How to Unhide files on Mac via Finder
~ defaults write com.apple.Finder AppleShowAllFiles true
~ killall Finder
ttps://setapp.com/how-to/show-hidden-files-on-mac
if want to back like before change true to false
~ defaults write com.apple.Finder AppleShowAllFiles false
~ killall Finder
2. Extract Zip file in FileManager
full code, following this code:
import UIKit
import Zip
class ExtraxtZipViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionview: UICollectionView!
var imagesIs = [UIImage]()
var zipURL: URL?
let fileManager = FileManager.default
override func viewDidLoad() {
super.viewDidLoad()
self.collectionview.register(UINib(nibName: "ImgInCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cellId")
do {
guard let _zip = zipURL else { return }
let unzipDirectory = try Zip.quickUnzipFile(_zip) // Unzip
let tempFiles = try fileManager.contentsOfDirectory(atPath: unzipDirectory.path)
tempFiles.forEach { _dataIs in
var removeThumb = _dataIs
if let range = removeThumb.range(of: "_thumb") {
removeThumb.removeSubrange(range)
}
if _dataIs == removeThumb {
let imageURL = URL(fileURLWithPath: unzipDirectory.path).appendingPathComponent(_dataIs)
guard let _image = UIImage(contentsOfFile: imageURL.path) else { return }
print("data---+4", _dataIs)
self.imagesIs.append(_image)
}
}
} catch {
print("Something went wrong")
}
self.collectionview.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.imagesIs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! ImgInCollectionViewCell
cell.layer.backgroundColor = UIColor.blue.cgColor
cell.imgIn.image = self.imagesIs[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 50, height: 50)
}
}
reference: https://stackoverflow.com/a/29005938/8366535
3. Remove string by word
for example with a dummy data, and looping data take a look number 2
var removeThumb = [1.png, 1_thumb.png, 2.png, 2_thumb.png]
if let range = removeThumb.range(of: "_thumb") {
removeThumb.removeSubrange(range)
}
print(
removeThumb) //1.png, 2.png
4. Get file in subFolder in file manager (After extract Zip File)
example normal checking :
let fileManager = FileManager.default let urlDir = URL(string: "your url file manager") do { let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL let tempFiles = try fileManager.contentsOfDirectory(atPath: urlDir.path) // main folder tempFiles.forEach { _data in do { let subFolder = URL(string: "\(documentsUrl)\(_data)") let _tempFiles = try fileManager.contentsOfDirectory(atPath: (subFolder?.path)!) // Sub folder print(_tempFiles) } catch { print("Something went wrong sub \(error.localizedDescription)") } } catch { }
example sub folder after unzip file:
do
{
guard let _zip = zipURL else { return }
let unzipDirectory = try Zip.quickUnzipFile(_zip) // Unzip
let tempFiles = try fileManager.contentsOfDirectory(atPath: unzipDirectory.path)
if tempFiles.count < 3 {
tempFiles.forEach { _data in
do {
let errSt = URL(string: "\(unzipDirectory)\(_data)")
let _tempFiles = try fileManager.contentsOfDirectory(atPath: (errSt?.path)!)
self.tempFilesInto(temp: _tempFiles, unzipUrl: errSt!)
} catch {
print("Something went wrong sub \(error.localizedDescription)")
}
}
} else {
self.tempFilesInto(temp: tempFiles, unzipUrl: unzipDirectory)
}
} catch {
print("Something went wrong \(error.localizedDescription)")
}
5. How to get filename image / imageView in Swift
This example how to get image filename. this will give you the file name and file extension directly
- from library
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let asset = info["UIImagePickerControllerPHAsset"] as? PHAsset{
if let fileName = asset.value(forKey: "filename") as? String{
print(fileName)
}
}
}
https://stackoverflow.com/a/47246490/8366535- from file manager (directory)
let fileManagerUrl: URL? = nil
override func viewDidLoad() {
super.viewDidLoad()
let myImageView = UIImageView()
guard let _image = UIImage(contentsOfFile: fileManagerUrl?.path ?? "") else {return}
myImageView.image = _image
print(fileManagerUrl?.lastPathComponent, "<- name image in last path") // image01.png <- name image in last path
}
- from asset
let myImageView = UIImageView()
myImageView.image = UIImage(named: "germany")
myImageView.restorationIdentifier = "germany" // Same name as image's name!
// Later, in UI Tests:
print(myImageView.restorationIdentifier!) // Prints "germany"
https://stackoverflow.com/a/44132821/83665356. Filter character type number in string
import UIKit
class DayStringViewController: UIViewController {
let png = "8.png"
override func viewDidLoad() {
super.viewDidLoad()
let numItemId = png.filter { "0123456789".contains($0) }
print(numItemId) // 8
}
}
7. Difference between strong and weak in swift
- Strong
A strong reference is like creating a new root for the tree, increasing it’s retain count by 1 and further ensuring it won’t be destroyed. Run in playground
import Foundation class Singer { func playSong() { print("Shake it off!") // data } } func sing() -> () -> Void { let taylor = Singer() let singing = { taylor.playSong() return } return singing } let singFunction = sing() singFunction() // Shake it off!
- Weak
A weak reference is like observing the tree from afar. You can still perform all the same functions on it, but have no control over keeping it rooted and thereby ensuring it is not destroyed. If all its strong references are removed, you won’t be able to access the object. Run in playground
import Foundation
class Singer {
func playSong() {
print("Shake it off!") // data
}
}
func sing() -> () -> Void {
let taylor = Singer()
let singing = { [weak taylor] in
taylor?.playSong()
return
}
return singing
}
let singFunction = sing()
singFunction() // Done
When use strong you can get from another viewController, but weak is not.Why create weak references?
Every strong reference and retained object increases your app’s memory usage and will affect performance. Weak references, when used properly, are a way to manage your app’s footprint.
You can capture value as both strong and weak if you're not sure which to use. You may choose either strong or weak, but not both.
reference:
https://medium.com/@janakmshah/the-difference-between-weak-strong-in-swift-2c953cedd7c0
8. Tap Link (Auto Filter Link)
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
let str = "Hi! Ryan noir invites you. https://scripttes.blogspot.com"
override func viewDidLoad() {
super.viewDidLoad()
textView.isSelectable = true
textView.isEditable = false
textView.dataDetectorTypes = .link
textView.textContainerInset = UIEdgeInsets.zero
textView.linkTextAttributes = [
NSAttributedString.Key.underlineColor: UIColor.red,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
]
textView.text = str
textView.font = UIFont.systemFont(ofSize: 24)
}
}
9. Error In Code "inout String"
if you found error like this
Error :
Cannot convert value of type 'String?' to expected argument type 'inout String'
Solution: remove "?" question mark
// from
@NSManaged public var name: String?
// to
@NSManaged public var name: String
And result in belowBefore
After
No comments: