#swift-6 利用 iOS SDK 各式型別生成東西

技術筆記

playground:
liveView //顯示某個 controller 或某個 view 的畫面

播音樂:
AVFoundation //import後才可播放音樂
URL(string: ) //要播放的音樂
AVPlayer(url: ) //讀取url的音樂
.play() //播放

播影片:
AVKit //import後才可播放影片
AVPlayerViewController //用來播放影片

顯示網頁:
SafariServices //import後才可使用Safari開啟網頁
SFSafariViewController //使用Safari開啟網頁

時間:
Date() //得到現在的時間
.addTimeInterval(X) //加X秒(X為數字)
DateFormatter() //可設定時間顯示的格式
.dateFormat //指定要顯示的格式
Calendar.current //取得現在的月曆
.dateComponents //取得型別DateComponents 的資料(包含詳細的時間資料)

播放音樂

import AVFoundation//URL:某個資源的位置(location of a resource),可以是網頁的網址,或是 App 裡檔案的路徑
let url = URL(string: "https://audio-ssl.itunes.apple.com/apple-assets-us-std-000001/AudioPreview118/v4/69/0e/98/690e98db-440d-cb0c-2bff-91b00a05bdda/mzaf_1674062311671795807.plus.aac.p.m4a")
let player = AVPlayer(url: url!)player.play()

播放影片

import AVKitimport PlaygroundSupportlet url = URL(string: "https://video-ssl.itunes.apple.com/itunes-assets/Video117/v4/fb/dd/1a/fbdd1a0f-d757-7d9e-a210-2548f19961df/mzvf_6805367839347105645.640x478.h264lc.U.p.m4v")let player = AVPlayer(url: url!)let controller = AVPlayerViewController()controller.player = playerPlaygroundPage.current.liveView = controllerplayer.play()

顯示網頁

import SafariServicesimport PlaygroundSupportlet url = URL(string: "https://www.youtube.com/")let controller = SFSafariViewController(url: url!)PlaygroundPage.current.liveView = controller

時間

在程式裡 Date 型別的東西代表時間,由於 Date 是在 Foundation 裡定義,所以須 import Foundation。

時間加減

import Foundationvar time = Date()print(time)time.addTimeInterval(((3*60)+50)*60+20) //距離現在3小時50分20秒print(time)

var time = Date()
利用 Date() 得到現在的時間。

time.addTimeInterval(91)
在 Date 資料上增加秒數。

時間格式

import Foundationlet now = Date()let dateFormatter = DateFormatter()dateFormatter.dateFormat = "yyyy年MM月dd日"let dateString = dateFormatter.string(from: now)

let dateFormatterObj = DateFormatter()
DateFormatter 可設定時間顯示的格式。

dateFormatterObj.dateFormat = "yyyy年MM月dd日"
.dateFormat指定要顯示的格式。

取得時間相關資訊

import Foundationlet today = Date()let dateComponents = Calendar.current.dateComponents(in: TimeZone.current, from: today)let year = dateComponents.year //年let month = dateComponents.month //月let day = dateComponents.day //日let weekday = dateComponents.weekday //星期(數字 1 是星期天,2 是星期一,以此類推。)

let dateComponents = Calendar.current.dateComponents(in:TimeZone.current,from:today")
Calendar.current 取得現在的月曆。
function dateComponents 將回傳型別 DateComponents 的資料(包含詳細的時間資料,ex:年月日時分秒…等)。

--

--