作業5#42 利用 iOS SDK 各式型別生成東西,設定它的屬性和呼叫方法

學習利用 iOS SDK 各式型別生成東西,設定它的屬性和呼叫方法

用 AVPlayer 播音樂

import AVFoundationlet url = URL(string: "https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview115/v4/6d/30/c1/6d30c138-1568-c3cf-3972-04938594ea37/mzaf_16173777020470120503.plus.aac.p.m4a")
let player = AVPlayer(url: url!)
player.play()

播放的是下面這首-艾怡良【我這個人】

用 AVPlayerViewController 播影片

import AVKitimport PlaygroundSupportlet url = URL(string: "https://movietrailers.apple.com/movies/universal/the-boss-baby-family-business/boss-baby-2-trailer-2_h480p.mov")let player = AVPlayer(url: url!)let controller = AVPlayerViewController()controller.player = playerPlaygroundPage.current.liveView = controllerplayer.play()

利用 SFSafariViewController 顯示網頁

import SafariServices
import PlaygroundSupport
let url = URL(string: "https://www.youtube.com/watch?v=4koqwFYcpTo")
let controller = SFSafariViewController(url: url!)
PlaygroundPage.current.liveView = controller

顯示地圖&加入地圖標記

import MapKit
import PlaygroundSupport
let mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
mapView.region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 25.081284, longitude: 121.237479), latitudinalMeters: 5000, longitudinalMeters: 5000)
let tag = MKPointAnnotation()
tag.coordinate = CLLocationCoordinate2D(latitude: 25.081284, longitude: 121.237479)
tag.title = "桃園機場"
tag.subtitle = "Airport"
mapView.addAnnotation(tag)
PlaygroundPage.current.liveView = mapView

列印時間

計算距離現在3小時50分20秒的時間。 — -(13820秒)

import Foundationvar time = Date()
print(time)
time.addTimeInterval(13820)
print(time)

將時間變成特定格式的字串

import Foundation
let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "EEEE, MMM d, yyyy"
let dateString = formatter.string(from: now)

取得今天幾月幾號的數字

  1. 取得今天年份的數字。

let year = dateComponents.year

  1. 取得今天星期幾的數字。

let weekday = dateComponents.weekday

值得一提的是系統預設一個禮拜的第一天是星期天,所以雖然這天是星期五但是找出來的結果會是“6“。

import Foundationlet today = Date()
let dateComponents = Calendar.current.dateComponents(in: TimeZone.current, from: today)
let month = dateComponents.month
let day = dateComponents.day
let year = dateComponents.year
let weekday = dateComponents.weekday

用 AVSpeechSynthesizer 講話

再用回第一首歌的歌詞來練習

import AVFoundationlet speech = AVSpeechUtterance(string: "我是否還值得被愛一次呢 多難過我都不准再對誰提起了")
speech.voice = AVSpeechSynthesisVoice(language: "zh-TW")
speech.rate = 0.3
speech.pitchMultiplier = 1.1
let talk = AVSpeechSynthesizer()
talk.speak(speech)

--

--