skip to Main Content

I’m using this code to pick video or image using PhotosPicker:

PhotosPicker(
    selection: $selectedItem,
    matching: matching: .any(of: [.images, .videos]),
    photoLibrary: .shared()) {
        Text("edit")
            .padding(.horizontal, 18)
            .padding(.vertical, 2)
            .background(Color.black.opacity(0.5))
            .cornerRadius(12)
    }
    .onChange(of: selectedItem) { newItem in
        Task {
            if let data = try? await newItem?.loadTransferable(type: Data.self) {
                selectedFileData = data
                // mimeType = ???
                          
            }
        }
    }

How can I find out the mime Type from the selected file? I know how to get it when I have the path/url of the selected file but I don’t know how to get it with PhotosPicker either

3

Answers


  1. By passing the reference URL path to this method you can get picked image or video MIME type

    func mimeTypeForPath(path: String) -> String {
      let url = NSURL(fileURLWithPath: path)
      let pathExtension = url.pathExtension
    
      if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension! as NSString, nil)?.takeRetainedValue() {
         if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
                return mimetype as String
         }
      }
        return "image/png"
    }
    

    I hope it may help you…

    Login or Signup to reply.
  2. Struggling with the same issue.

    It looks like we can access var supportedContentTypes: [UTType] { get } from PhotosPickerItem

    The content types the item supports in order of the most preferred to the least.

    https://developer.apple.com/documentation/photokit/photospickeritem/4022920-supportedcontenttypes

    item.supportedContentTypes.first?.preferredMIMEType // Optional("image/jpeg")
    

    Better than nothing I guess.

    Login or Signup to reply.
  3. I found a way. You can check item supported type and custom handle. Try replace your Task in onChange to this:

    Task {
        if let data = try? await newItem?.loadTransferable(type: Data.self) {
            selectedFileData = data
        }
        guard let type = newItem?.supportedContentTypes.first else {
            print("There is no supported type")
        }
        if type.conforms(to: UTType.image) {
            // Handle any image type
        } else if type.conforms(to: UTType.video) {
            // Handle video type
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search