2017-05-05 3 views
5

documentPicker를 사용하여 문서의 URL 경로를 얻은 다음 데이터베이스에 업로드했습니다. 파일 (pdf, txt ..)을 선택합니다. 업로드가 작동하지만 파일 크기를 제한하려고합니다.Swift - url에서 파일 크기 얻기

public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { 

     self.file = url //url 
     self.path = String(describing: self.file!) // url to string 
     self.upload = true //set upload to true 
     self.attachBtn.setImage(UIImage(named: "attachFilled"), for: .normal)//set image 
     self.attachBtn.tintColor = UIColor.black //set color tint 
     sendbtn.tintColor = UIColor.white // 


     do 
     { 
      let fileDictionary = try FileManager.default.attributesOfItem(atPath: self.path!) 
      let fileSize = fileDictionary[FileAttributeKey.size] 
      print ("\(fileSize)") 
     } 
     catch{ 
      print("Error: \(error)") 
     } 

    } 

나는 문서 선택기 파일 어떻게 자신의 속성을 검색하는 방법을 절약 할 오류 메시지,이 파일이 존재하지 않는 얻을.

+0

아마도 이것이 당신이 찾고있는 것입니다 : http://stackoverflow.com/questions/19315533/how-to-find-size-of-a-file-before-downloading-it-in-ios -7 –

+0

감사합니다. 링크가 도움이되었습니다. –

+0

iOS 11의 –

답변

11

우선 파일 시스템에서 path 속성을 가진 URL 경로를 얻습니다.

self.path = url.path 

하지만 전혀 필요하지 않습니다. 당신은 직접 URL에서 파일 크기를 검색 할 수 있습니다

self.path = String(describing: self.file!) // url to string

그것은 바이트 카운터 포맷터 사용하여 파일의 크기를 계산하기 위해 신속의 최신 버전으로 매우 쉽게
do { 
    let resources = try url.resourceValues(forKeys:[.fileSizeKey]) 
    let fileSize = resources.fileSize! 
    print ("\(fileSize)") 
} catch { 
    print("Error: \(error)") 
} 
+0

을 환영합니다. Error Domain = NSCocoaErrorDomain Code = 257 "권한이 없기 때문에 파일을 열 수 없습니다." – Sneha

0

:

var에 fileSizeValue를 : UINT64 = 0

do { 

     let fileAttribute: [FileAttributeKey : Any] = try FileManager.default.attributesOfItem(atPath: url.path) 

     if let fileNumberSize: NSNumber = fileAttribute[FileAttributeKey.size] as? NSNumber { 
      fileSizeValue = UInt64(fileNumberSize) 

      let byteCountFormatter: ByteCountFormatter = ByteCountFormatter() 
      byteCountFormatter.countStyle = ByteCountFormatter.CountStyle.file 

      byteCountFormatter.allowedUnits = ByteCountFormatter.Units.useBytes 
      print(byteCountFormatter.string(fromByteCount: Int64(fileSizeValue))) 

      byteCountFormatter.allowedUnits = ByteCountFormatter.Units.useKB 
      print(byteCountFormatter.string(fromByteCount: Int64(fileSizeValue))) 

      byteCountFormatter.allowedUnits = ByteCountFormatter.Units.useMB 
      print(byteCountFormatter.string(fromByteCount: Int64(fileSizeValue))) 

     } 

    } catch { 
     print(error.localizedDescription) 
    } 
2

스위프트 4

,536,
func sizePerMB(url: URL?) -> Double { 
    guard let filePath = url?.path else { 
     return 0.0 
    } 
    do { 
     let attribute = try FileManager.default.attributesOfItem(atPath: filePath) 
     if let size = attribute[FileAttributeKey.size] as? NSNumber { 
      return size.doubleValue/1000000.0 
     } 
    } catch { 
     print("Error: \(error)") 
    } 
    return 0.0 
}