iosswiftuploadphotokit

When uploading a large file from PHAsset, do I need to copy it a temp file?


I am trying to upload a file from an iOS device through Google resumable upload feature. What I've tried is the methods of PhotoKit and uploadTask(with:fromFile).

extension ExampleViewController: PHPickerViewControllerDelegate {
    public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        ....
        let identifiers = results.compactMap { $0.assetIdentifier }

        identifiers.forEach { identifier in 
            getFileUrlFromPHAsset(assetIdentifier: identifier) { fileUrl in 
                // googleSessionUri is a url to upload a file to
                var request = URLRequest(url: URL(string: googleSessionUriToUpload)!)
                request.method = .put
                let task = urlSession.uploadTask(with: request, fromFile: fileUrl)
                task.resume()
            }
        }
    }
}

func getFileUrlFromPHAsset(assetIdentifier: String, completion: ((URL) -> Void)) {
    guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [assetIdentifier], options: nil).firstObject else {
        return 
    }
            
    let option = PHVideoRequestOptions()
    option.isNetworkAccessAllowed = true // for icloud files? not sure
    PHImageManager.default().requestAVAsset(forVideo: asset, options: option, resultHandler: { avAsset, _, _ in
        if let urlAsset = avAsset as? AVURLAsset {
            completion(urlAsset.url)
        } else {
            // TODO: error handling..
        }
    })      
}

but I got an error BackgroundSession <D4B1D24E-B567-4935-8589-40FF99845CD6> Failed to issue sandbox extension for file file:///var/mobile/Media/DCIM/100APPLE/IMG_0030.MOV, errno = [1: Operation not permitted].

Should I copy this PHAsset to a temp file to upload? Then how can I manage the risk that the temp file might consume the disk space? For my case, the video files are quite large, roughly Gigabytes size. In an extreme case where the device has not enough space, the upload might not be able to even start then.

Thanks in advance.


Solution

  • If you worry about space insufficient,try converting the video to data then uploading it using multipart technique.