FileDownload in swift

2022. 6. 10. 13:09· 개발/JongjuAR
목차
  1. Source
  2. References

Source

//
//  Util.swift
//  JongjuAR
//
//  Created by 전민정 on 6/9/22.
//

import Foundation
import UIKit

// Gpx File download
func DownloadGpx(gpxPath: String, gpxFile: String) -> Bool {
    // url 유효한지 확인 비어있으면 비었다고
    var result = false
    let url = URL(fileURLWithPath: gpxPath)
    
    URLSession.shared.dataTask(with: url) { data, resp, err in
        guard let resp = resp as? HTTPURLResponse else {
            print("Not http url...")
            return }
        if (200..<300).contains(resp.statusCode) { // url 유효
            // download
            result = DownloadFileFromUrl(urlPath: gpxPath, savedName: gpxFile)
        } else {
            return
        }
    }.resume()
            
    return result
}

func DownloadFileFromUrl(urlPath: String, savedName: String) -> Bool {
    
    var result = false
    // Create destination URL
    let documentsUrl: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let destinationFileUrl = documentsUrl.appendingPathComponent("JongjuAR").appendingPathComponent(savedName)
    
    // Create URL to the source file you want to download
    let fileURL = URL(string: urlPath)
    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)
    let request = URLRequest(url:fileURL!)
    
    // Make folder specified this app
    let folderPath = documentsUrl.appendingPathComponent("JongjuAR")
    if !FileManager.default.fileExists(atPath: folderPath.path) {
        do {
            try FileManager.default.createDirectory(atPath: folderPath.path, withIntermediateDirectories: true)
        } catch {
            print("Coundn't create directory for this app...")
        }
    }
    
    // Download file
    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success
            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Successfully downloaded. Status code: \(statusCode)")
            }
            
            do {
                try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
            } catch (let writeError) {
                print("Error creating a file \(destinationFileUrl) : \(writeError)")
            }
            result = true
        } else {
            print("Error took place while downloading a file. Error description: %@", error?.localizedDescription as Any);
        }
    }
    task.resume()
    
    return result
}

// Search Gpx file
func IsDownloaded(gpx: String) -> Bool {
    // 저장해놓는 폴더 경로에서 찾아보기.
    
    // Create destination URL
    let documentsUrl: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let destinationFileUrl = documentsUrl.appendingPathComponent("JongjuAR").appendingPathComponent(gpx)
    
    // Make folder specified this app if folder is not exists
    let folderPath = documentsUrl.appendingPathComponent("JongjuAR")
    if !FileManager.default.fileExists(atPath: folderPath.path) {
        do {
            try FileManager.default.createDirectory(atPath: folderPath.path, withIntermediateDirectories: true)
        } catch {
            print("Coundn't create directory for this app...")
        }
    }
    
    // Check exists
    if FileManager.default.fileExists(atPath: destinationFileUrl.path) {
        return true
    } else {
        return false
    }
}

References

https://stackoverflow.com/questions/58048820/how-to-know-if-an-url-is-valid-and-also-check-it-will-be-open-or-not-in-swift

 

How to know if an URL is valid And Also check it will be open or not in swift

In my Project I need to save a user given url. So I need to check if it's a valid URL and most importantly if it will be open in a WKWebView. My Problem: I can verify an url but can't make sure it ...

stackoverflow.com

https://www.appsdeveloperblog.com/download-file-from-a-remote-url-in-swift/

 

Download File From a Remote URL in Swift. - Apps Developer Blog

With this short Swift code example, I am going to share with you how to download a large file from a remote URL. It could be an image file, video file, or even a ZIP archive of a large size. The Swift code example below will cover the following: Create a d

www.appsdeveloperblog.com

https://zeddios.tistory.com/440

 

iOS ) FileManager를 이용해 파일/폴더 만드는 법

안녕하세요 :) Zedd입니다. 제목이 뭔가 추상적인데.....이 글은...저를 위한....공부... FileManager를 이용해 파일/폴더 만드는 법 파일 및 디렉토리와 관련된 가장 기본적인 작업 중 일부는 파일 시스

zeddios.tistory.com

https://www.appsdeveloperblog.com/check-if-a-file-exist/

 

Check if a File Exist - Apps Developer Blog

In this Swift tutorial, you will learn how to check if a file at the secified path exists.

www.appsdeveloperblog.com

 

728x90
반응형

'개발 > JongjuAR' 카테고리의 다른 글

Json Decode  (0) 2022.06.09
Pod 설치  (0) 2022.06.06
  1. Source
  2. References
'개발/JongjuAR' 카테고리의 다른 글
  • Json Decode
  • Pod 설치
내공얌냠
내공얌냠
내공냠냠
내공얌냠
내공냠냠
내공얌냠
전체
오늘
어제
  • 분류 전체보기 (255) N
    • 개발 (113)
      • mediapipe (16)
      • insightface (5)
      • JongjuAR (3)
    • 자료구조 알고리즘 (79)
      • 코딩테스트 (64)
      • 이론 (15)
    • 공부 (54) N
      • 단행본 (8) N
      • 튜토리얼 (19)
      • 논문 (15)
      • 복기 (5)
    • 참여 (5)

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 플러터 튜토리얼
  • postgresql 재설치
  • speaker adaptation tts
  • 음성인식 튜토리얼
  • 구글 미디어파이프
  • 컴퓨터 비전
  • 음성인식 기초
  • 깃 튜토리얼
  • vscode 스프링 설치
  • 컴퓨터 비전 기초
  • 테디노트 rag 기본편
  • flutter 행사 후기
  • google mediapipe
  • flutter conference
  • ios google places api
  • 컴퓨터 비전 책 추천
  • flutter
  • 딥러닝 기반 음성인식 기초
  • mediapipe translate
  • 미디어파이프
  • 플러터
  • 머신러닝이란
  • 테디노트의 랭체인을 활용한 rag 비법노트 기본편 후기
  • flutter 행사
  • flutter tutorial
  • 테디노트의 랭체인을 활용한 rag 비법노트 기본편
  • mediapipe
  • python telegrambot
  • postgresql install in mac
  • git tutorial

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.2
내공얌냠
FileDownload in swift
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.