iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 15
0
自我挑戰組

老蕭咖啡館,情境式學習基礎iOS Swift系列 第 15

[2019鐵人賽Day15]老蕭咖啡館-實作篇「簡易相機」

既然提到了Info.plist屬性,那我們就來試著做看看簡易「相機」功能!!


Step1. 先建立一個新專案,名稱為「camera」
https://ithelp.ithome.com.tw/upload/images/20181030/200913333wfQVyFfJW.png

Step2. Info.plist 新增「相機」、「相簿」(有兩項)權限
https://ithelp.ithome.com.tw/upload/images/20181030/20091333PvrqNi70i4.png

使用「相機」NSCameraUsageDescription
https://ithelp.ithome.com.tw/upload/images/20181030/20091333FfBEtFhw5O.png

使用「相簿」NSPhotoLibraryUsageDescription
https://ithelp.ithome.com.tw/upload/images/20181030/20091333eVUhFjSBJa.png

寫入「相簿」NSPhotoLibraryAddUsageDescription
https://ithelp.ithome.com.tw/upload/images/20181031/20091333YqlJQ6pcBg.png

https://ithelp.ithome.com.tw/upload/images/20181031/20091333OA6L0MkUXE.png

Step3. 而這次的主角是「ViewController.swift」、「Main.storyboard」
在「Main.storyboard」新增個Button元件
接著開啟「輔助設計模式」將Button連結,命名為「openCamera」
https://ithelp.ithome.com.tw/upload/images/20181031/20091333jaLm0FALSN.png

https://ithelp.ithome.com.tw/upload/images/20181031/20091333AtgZ3QcPaa.png

https://ithelp.ithome.com.tw/upload/images/20181031/20091333x1mrpxh9ol.png

Step4. 在「openCamera」內加入以下動作
「.camera」照片來自於相機拍攝
「.photoLibary」 照片來自於已儲存的照片
https://ithelp.ithome.com.tw/upload/images/20181031/20091333KuCU7UDyBa.png

// 檢查是否具有照相功能
if UIImagePickerController.isSourceTypeAvailable(.camera){
    let imagePicker = UIImagePickerController()

    // 設置相片來源為相機
    imagePicker.sourceType = .camera
    imagePicker.delegate = self

    //開啟相機
    show(imagePicker, sender: self)
}

Step5. 接著在下方加入如圖代碼,已控制儲存相片
https://ithelp.ithome.com.tw/upload/images/20181031/200913338mYs0eM1kK.png

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    // 取得相片
    let image = info[.originalImage] as! UIImage

    // 儲存相片
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
    dismiss(animated: true, completion: nil)
}

Step6. Finish
https://ithelp.ithome.com.tw/upload/images/20181031/200913337wlOWGIdKo.jpg

https://ithelp.ithome.com.tw/upload/images/20181031/20091333Ul8fyrjShh.jpg

https://ithelp.ithome.com.tw/upload/images/20181031/20091333p1E4EgdlJh.jpg


有否注意到,App的名稱不是預設的字樣了
左側點擊專案->「Display Name」填入想要顯示的App名稱
https://ithelp.ithome.com.tw/upload/images/20181031/20091333aumcv2t2R6.png


上一篇
[2019鐵人賽Day14]老蕭咖啡館-簡易說明Info.plist屬性
下一篇
[2019鐵人賽Day16]老蕭咖啡館-實作篇,簡易查看相簿
系列文
老蕭咖啡館,情境式學習基礎iOS Swift30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言