20220108のSwiftに関する記事は4件です。

Finderの「サーバへ接続」の「よく使うサーバ」リストに一括追加する

Finderの「サーバへ接続」画面において,+ ボタンを押すと,「よく使うサーバ」にサーバのURLを追加できます。 ここに登録したいサーバがたくさんあるとき,コマンドで一括追加したくなります。 かつては, $ /usr/bin/sfltool add-item -n "hoge" com.apple.LSSharedFileList.FavoriteServers "smb://hoge@192.168.0.100" のようなコマンドで「よく使うサーバ」リストに追加ができました。これにより,~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.FavoriteServers.sfl2 にサーバのエントリが追記されたのです。 これをシェルスクリプトにしておけば,よく使うサーバを大量に一括登録できたのですが,なんと,macOS 10.13 以降,sfltool コマンドに add-item というサブコマンドは廃止され,復活の予定はないそうです。 そこで,com.apple.LSSharedFileList.FavoriteServers.sfl2 にエントリを追加するには,結構面倒なプログラミングが必要になりました。Swiftコードで書くとこのようになります(エラー処理はテキトーです)。 import Foundation let error = NSError(domain: "error", code: -1, userInfo: nil) let sflURL = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library").appendingPathComponent("Application Support").appendingPathComponent("com.apple.sharedfilelist").appendingPathComponent("com.apple.LSSharedFileList.FavoriteServers.sfl2") func readFavoriteServers() throws -> (items: NSArray, properties: NSDictionary, existingURLs: [URL]) { guard let dict = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(Data(contentsOf: sflURL)) as? NSDictionary, let items = dict["items"] as? NSArray, let properties = dict["properties"] as? NSDictionary else { throw error } // 型情報 // dict: NSDictionary<NSString*,id>* // items: NSArray<NSDictionary<NSString*,id>*>* // properties: NSDictionary<NSString*,id>* let existingURLs: [URL] = items.compactMap { item in var stale: Bool = false guard let item = item as? NSDictionary, let data = item["Bookmark"] as? Data, let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale) else { return nil } return url } return (items: items, properties: properties, existingURLs: existingURLs) } func addFavoriteServer(_ paths: String...) throws { guard let (oldItems, properties, existingURLs) = try? readFavoriteServers() else { throw error } let uniqueURLs = Set(existingURLs) print("Existing items: " + existingURLs.description) let newItems = NSMutableArray(array: oldItems) paths.forEach { path in guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: encodedPath), let bookmark = try? url.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil) else { return } let entry: [String:Any] = [ "Name": path, "Bookmark": bookmark, "uuid": UUID().uuidString, "visibility": 0, "CustomItemProperties": NSDictionary() ] if uniqueURLs.contains(url) { print("Skip: " + path) } else { newItems.add(entry) print("Add: " + path) } } let newDict: [String:Any] = [ "items": newItems, "properties": properties ] do { try NSKeyedArchiver.archivedData(withRootObject: newDict, requiringSecureCoding: true).write(to: sflURL) } catch let e { throw e } } // main routine do { try addFavoriteServer("smb://192.168.100.1","smb://192.168.100.2","smb://192.168.100.3","smb://192.168.100.4") let (_, _, existingURLs) = try readFavoriteServers() print("New items: " + existingURLs.description) print("Restart your Mac for the changes to take effect!") } catch let e { print(e.localizedDescription) } このコードでは,最後のメインルーチンのところで addFavoriteServer("smb://192.168.100.1","smb://192.168.100.2","smb://192.168.100.3","smb://192.168.100.4") とすることで,サーバのURLを一括追加しています。addFavoriteServer は,引数に与えられたURLたちを,既存のサーバURLと照合して,既存のURLはスキップして,新しいURLのみだけを順に追加していきます。 この変更をFinderのUI上に反映させるためには,macOSの再起動が必要でした。(Finderの再起動だけで済むという話もありましたが,自分の環境ではOS全体を再起動しないと変更が反映されませんでした。)
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【SwiftUI】NavigationView の中の TabView の中の NavigationLink 先で Sheet を開くと NavigationLink が勝手に戻るバグの対処法

GIFの様に、 SecondView で Sheet を開くと FirstView に戻ってしまいます。 解消法は、 NavigationView → TabView を TabView → NavigationView に変えればOKです。 import SwiftUI struct FirstView: View { @State var selection = 0 var body: some View { // NG。勝手に戻る。 // NavigationView { // TabView(selection: $selection) { // OK。 TabView(selection: $selection) { NavigationView { NavigationLink(destination: SecondView()) { Text("Go to SecondView").font(.title) } .tag(0) } .navigationTitle("FirstView") } } } struct SecondView: View { @State var isPresented = false var body: some View { Button(action: { isPresented = true }) { Text("open sheet").font(.title) } .sheet(isPresented: $isPresented) { Text("sheet").font(.title) } .navigationTitle("SecondView") } } struct FirstView_Previews: PreviewProvider { static var previews: some View { FirstView() } } バージョン Xcode 13.1 iOS 15.0
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

enumとは

簡単にいうと型です。 列挙型と呼ばれるものになります。 enum Name { case akiyama, shiina, katou } 上記は何をしてるのか 要はこんな感じです。 enum Name { let akiyama: Name let shiina: Name let katou: Name } 複数の定数(列挙子)を一つの型で統一して管理できます※変数は不可 型を指定しない場合 型の名前は Nameという型で表示されます テキスト表示したいなら型を指定する必要がある 例えば上記の場合だとラベルとかに表示する時hashValueと呼ばれるものでしか表示ができません。 その場合、hashValueの型はIntなので謎の数字で答えが返ってきます。 なので、もし上記をラベルなどで表示したいとかそういう場合はenumの型をString型などに変える必要があります。 enum Name: String { case akiyama, shiina, katou } 呼び出し方 print(Name.akiyama.rawValue) 型を調べたいかた print(type(of: Name.akiyama.rawValue)) 理解力が微妙なので、引き続き修正していくと思います
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

小学生でも分かるswift構文2

小学生でも分かるswift構文2 さて、今回は数値型について記述していきたいと思います。 「int」とは、型の一種で、整数型と呼ばれています。 実際にXcode上で、 let integer:Int = 0 と入力してみました。 「integer」という名前の、「Int」型に「0」という値を代入しました。 という構文になります。 もう一つ紹介するのが、 「double」という型で、浮動小数点型と呼ばれます。 let ダブル:Double = 0.1 「ダブル」という名前の、「Double」型に「0.1」という値を代入しました。 という構文です。 小数点が付かない数は「Int」型,小数点が付く数は「Double」型を使うと思って頂ければ大丈夫です。 また、swiftには「型推論」という機能が備わっていて、 let integer = 0 のように入力しても、「integer」は「Int」型だとXcode側で勝手に判断してくれる便利な機能が備わっているのです。 僕自身、初心者すぎてこの機能の恩恵はよく解っていないのですが、恐らくたくさん構文を書いていけばいくほど、型をいちいち明示する手間が省けるので、すごくありがたい機能なんだと思います。 次回は実際に数値型を使って、計算を行っていきたいと思います。 では!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む