当前位置: 移动技术网 > IT编程>移动开发>IOS > Swift 共享文件操作小结(iOS 8 +)

Swift 共享文件操作小结(iOS 8 +)

2019年07月24日  | 移动技术网IT编程  | 我要评论

天下足球20140527,陕铁院教务处,毕福剑简历

前言

  适用于 ios 8 + 本地共享文件列表

正文

  一、准备

    1.1  默认 app 的文件共享是关闭的,需要在 plist 中设置启用:

    application supports itunes file sharing  设置为  yes

启用后把设备连接到 itunes 上,在 itunes 应用里的文件共享就能看到你的 app 了(如果看不见需要断开重新拔插一下数据线),可以拷贝一些视频进去,便于测试。

    1.2  导入库

      photos.framework

      avkit.framework  用于播放视频    

  二、获取视频列表

 private let video_extensions = [
    ".mov", ".mp4"
  ]

  private var filemanager = nsfilemanager.defaultmanager()
  
  func loadvideos() {
    var paths = nssearchpathfordirectoriesindomains(.documentdirectory, .userdomainmask, true)
    if paths.count > 0 {
      let documentsdirectory = paths[0] as string
      let documenturl = nsurl(fileurlwithpath: documentsdirectory, isdirectory: true)
      do {
        documenturl.path
        let files = try filemanager.contentsofdirectoryatpath(documentsdirectory)
        for file in files {
          fetchvideos(documenturl.urlbyappendingpathcomponent(file).path ?? "")
        }
      }  catch {
        
      }
      
      self.tableview.reloaddata()
    }
  }
  
  func fetchvideos(path: string) {
    var isdir: objcbool = false
    if !path.isempty && filemanager.fileexistsatpath(path, isdirectory: &isdir) {
      if isdir {
        do {
          let files = try filemanager.contentsofdirectoryatpath(path)
          for file in files {
            fetchvideos(file)
          }
        } catch {
        }
      } else {
        var file = file(path: path)
        if file.isvalid() && isvideofileextension(file.fileextension.uppercasestring) {
          do {
            if let attr: nsdictionary = try filemanager.attributesofitematpath(path) {
              file.filesize = attr.filesize()
            }
          } catch {
          }
          videos.append(file)
        }
      }
    }
  }
  
  func isvideofileextension(ext: string) -> bool {
    for videoextension in video_extensions {
      if ext == videoextension {
        return true
      }
    }
    return false
  }
  
  struct file {
    var fileextension = ""
    var filename = ""
    var path = ""
    var assert: avurlasset?
    var url: nsurl!
    var filesize: uint64 = 0
    
    init(path: string) {
      self.path = path
      self.url = nsurl(fileurlwithpath: path)
      self.filename = url.lastpathcomponent ?? ""
      self.fileextension = "." + (url.pathextension ?? "")
    }
    
    func isvalid() -> bool {
      return !(filename.isempty || fileextension.isempty)
    }
  }

代码说明:

      a)需要注意一些 swift 的用法,例如 fileexistsatpath 的用法

      b)还有 string 的 pathextension 和 lastpathcomponent 都没了,都改到了 nsurl 下面去了,网上很多资料都还是从 nsstring 或者 string 取这些属性

      c)avurlasset 可以取到视频的时长 cmtimegetseconds(avurlasset(url: file.url, options: nil).duration)

  三、播放视频

 func play(file: file) {
    let player = avplayer(url: file.url)
    let playerviewcontroller = avplayerviewcontroller()
    playerviewcontroller.player = player
    self.presentviewcontroller(playerviewcontroller, animated: true) {
      playerviewcontroller.player?.play()
    }
  }

        四、用 ... 打开

 func openin(file: file, indexpath: nsindexpath) {
    let document = uidocumentinteractioncontroller(url: file.url)
    let rect = self.tableview.rectforrowatindexpath(indexpath)
    document.presentopeninmenufromrect(rect, inview: self.tableview, animated: true)
  }

        五、删除视频

 func delete(file: file, indexpath: nsindexpath) {
    do {
      try filemanager.removeitematpath(file.path)
      videos.removeatindex(indexpath.row)
      tableview.deleterowsatindexpaths([indexpath], withrowanimation: uitableviewrowanimation.automatic)
    } catch {
      
    }
  }

        六、保存到相册

 func savetocameraroll(file: file, indexpath: nsindexpath) {
    if uivideoatpathiscompatiblewithsavedphotosalbum(file.path) {
      uisavevideoatpathtosavedphotosalbum(file.path, self, "image:didfinishsavingwitherror:contextinfo:", nil)
    } else {
      // save faild
    }
  }
  
  func image(image: uiimage, didfinishsavingwitherror error: nserrorpointer, contextinfo:unsafepointer<void>) {
    if error == nil {
      // save success
    } else {
      // save faild
    }
  }

 代码说明:

      注意 uisavevideoatpathtosavedphotosalbum 的用法,后面 selector 写得不对就会报错。

以上就是ios 8 共享文件的实例代码,有需要的朋友可以参考下。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网