| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

「Swift Sample」の版間の差分

提供: MyMemoWiki
ナビゲーションに移動 検索に移動
52行目: 52行目:
 
         }
 
         }
 
</pre>
 
</pre>
 +
[[File:swift_json_encode.png|300px]]
  
 
==UI==
 
==UI==

2021年4月27日 (火) 13:03時点における版

| Swift | SwiftUI |Xcode | Mac |

Swift Sample

Network

データ取得


  1. let url = URL(string: "https://www.typea.info/blog/")!
  2. let task = URLSession.shared.dataTask(with: url) { data, response, error in
  3. if let error = error {
  4. print("\(error)\n")
  5. return
  6. }
  7. guard let data = data, let response = response as? HTTPURLResponse else {
  8. print("no data or no response.")
  9. return
  10. }
  11. if response.statusCode == 200 {
  12. if let text = String(bytes: data, encoding: .utf8) {
  13. print(text)
  14. }
  15. }
  16. }
  17. task.resume()

MacOSでエラーの場合

Error Domain=NSURLErrorDomain Code=-1003

Swift macos net error.png

File

JSONにシリアライズしてドキュメントディレクトリへ書き出し

  • データ(Codableを適用する)
  1. struct Host : Codable {
  2. var host: String = ""
  3. var ip: String = ""
  4. var macaddr: String = ""
  5. }
  • 書き出し処理
  1. let docPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
  2. let filePath = URL(fileURLWithPath: "hosts.json", relativeTo:docPath)
  3. let encoder = JSONEncoder()
  4. do {
  5. let line = try encoder.encode(host)
  6. try line.write(to: filePath)
  7. } catch {
  8. print(error)
  9. }

Swift json encode.png

UI

バックグラウンドからUIを操作する


  • observableobj が、ObservableObject の派生クラス
  • contentフィールドに、@Published アノテーション
  • Viewで、@ObservedObjectを付与しインスタンスを生成
  • 上記で、バックグラウンドから、observableobj.contentを操作すると、UIはメインスレッドから触るように怒られる。

Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.

  • DispatchQueue.main.syncで囲む
  1. DispatchQueue.main.sync {
  2. observableobj.content = text
  3. }

処理

サブプロセスを起動

  • プロセスを起動し、arp -a を呼び出し、出力
  1. func arp() {
  2. let outputPipe = Pipe()
  3.  
  4. func shell(path:String ,args: String...) -> Int32 {
  5. let task = Process()
  6. task.launchPath = path
  7. task.arguments = args
  8. task.standardOutput = outputPipe
  9. task.standardError = outputPipe
  10. task.launch()
  11. task.waitUntilExit()
  12. return task.terminationStatus
  13. }
  14. let _ = shell(path:"/usr/sbin/arp",args: "-a")
  15. let theTaskData = outputPipe.fileHandleForReading.readDataToEndOfFile()
  16. let stringResult = String(data: theTaskData, encoding: .utf8)
  17. print(stringResult!)
  18. }

正規表現

arp -a の結果からIPアドレスを抜きだす


  1. func parseArp(arpResult: String?) {
  2. if let input = arpResult {
  3. do {
  4. let pattern = #"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"#
  5. let regex = try NSRegularExpression(pattern: pattern, options:[])
  6. for subinput in input.split(separator: "\r\n") {
  7. let line = String(subinput)
  8. let maches = regex.matches(in: line, options: [], range: _NSRange(0..<line.count))
  9. print(line)
  10. for mach in maches {
  11. for i in 0 ..< mach.numberOfRanges {
  12. let start = line.index(line.startIndex, offsetBy: mach.range(at: i).location)
  13. let end = line.index(start, offsetBy: mach.range(at: i).length)
  14. let text = String(line[start..<end])
  15. print(text)
  16. }
  17. }
  18. }
  19. } catch {
  20. print("RegEx fail.")
  21. }
  22. } else {
  23. print("arp -a result : error")
  24. }

名前を付与してキャプチャ


  1. func parseArp(arpResult: String?) {
  2. if let input = arpResult {
  3. do {
  4. let pattern = #".*?(?<ip>[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*(?<mac>[0-9a-z]{1,2}:[0-9a-z]{1,2}:[0-9a-z]{1,2}:[0-9a-z]{1,2}:[0-9a-z]{1,2}:[0-9a-z]{1,2})"#
  5. let regex = try NSRegularExpression(pattern: pattern, options:[])
  6. for subinput in input.split(separator: "\r\n") {
  7. let line = String(subinput)
  8. let matches = regex.matches(in: line, options: [], range: _NSRange(0..<line.count))
  9. print(line)
  10. for match in matches {
  11. for name in ["ip", "mac"] {
  12. let matchRange = match.range(withName: name)
  13. if let substrRanget = Range(matchRange, in:line) {
  14. let ip = String(line[substrRanget])
  15. print("\(name):\(ip)")
  16. }
  17. }
  18. }
  19. }
  20. } catch {
  21. print("RegEx fail.")
  22. }
  23. } else {
  24. print("arp -a result : error")
  25. }
  26. }