카테고리 없음

IOS) Server(서버에서 앱으로 이미지 다운로드 방법 ) (버튼 + ImageView) + 아파치 톰캣 필요 ( 터미널로 starup.sh)

Chain X 2020. 9. 2. 14:46
728x90
반응형

01
기능설명
012
버튼 + ImageView)

 

//
//  ViewController.swift
//  ServerImage_01
//
//  Created by Mac on 2020/09/02.
//  Copyright © 2020 MyMac. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    
    @IBOutlet weak var imgDisplay: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    // 버튼 클릭 했을 때 이미지가 들어온다.
    @IBAction func btnLoadImage(_ sender: UIButton) {
        downloadItems()
    }
    
    func downloadItems(){
        let url = URL(string: "http://127.0.0.1:8080/Test/img_0214.jpg")!
        let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
        
        let task = defaultSession.dataTask(with: url){(data,response, error)in
            if error != nil{
                print("Falied to download data")
            }else{
                print("Data is downloaded")
                DispatchQueue.main.async {
                    self.imgDisplay.image = UIImage(data: data!)
                    // jpg
                    if let image = UIImage(data: data!){ // nil 값이면 빠진다.
                        if let data = image.jpegData(compressionQuality: 0.8){
                            let filename = self.getDocumentDirectory().appendingPathComponent("copy.jpg")
                            try? data.write(to: filename)
                            print("Data is writed")
                            print(self.getDocumentDirectory())
                        }
                    }
                    // 앱만들 때 서버에 이런 이미지가 있다.  서버에 이미지 만들어 넣고 앱으로 다운로드 한다.
                    // 앱으로 만든다면 프린트를 막아준다. 프린트는 퍼포먼스를 많이 잡아 먹는다. 즉 느려진다.
                    
                    //png
//                    if let image = UIImage(data: data!){ // nil 값이면 빠진다.
//                        if let data = image.pngData{
//                          let filename = self.getDocumentDirectory().appendingPathComponent("copy.jpg")
//                                try? data.write(to: filename)
//                                print("Data is writed")
//                                 print(self.getDocumentDirectory())
//                              }
//                        }
                }
            }
        }
        task.resume()
    }
    
    // 스마트폰의 write 위치를 알려주는 함수
    func getDocumentDirectory() -> URL{
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
        
    }
    
} /////////////-------------

반응형