The file “xxx.mp4” couldn’t be opened because you

2019-03-28 12:18发布

问题:

I use the Alamofire method multipartFormData.append(URL, withName: "file") to upload a video to the server but I've got an error message:

multipartEncodingFailed(Alamofire.AFError.MultipartEncodingFailureReason.bodyPartFileNotReachableWithError(file:///var/mobile/Media/DCIM/100APPLE/IMG_0939.mp4, Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_0939.mp4” couldn’t be opened because you don’t have permission to view it." UserInfo={NSURL=file:///var/mobile/Media/DCIM/100APPLE/IMG_0939.mp4, NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0939.mp4, NSUnderlyingError=0x174450d10 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}))

I have opened that Privacy - Photo Library Usage Description but I got this error and I don't have any idea.

My code:

alamofireManager?.upload(
    multipartFormData: { multipartFormData in
        for i in 0..<videoURLs.count {
            multipartFormData.append(videoURLs[i], withName: "file")
        }
    },
    to: url + urlString,
    headers: headers,
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.uploadProgress(closure: { (progress) in


                //Print progress
                //print(progress)
            })

            upload.responseJSON { response in
                if let value = response.result.value as? [String: AnyObject]{
                    success(value)
                }
            }
        case .failure(let encodingError):
            failture(encodingError)
        }
    }
)

回答1:

You need to use startAccessingSecurityScopedResource

if let url = file.url, url.startAccessingSecurityScopedResource() {
    multipartFormData.append(url, withName: "some-file.pdf")
    // After using the resource make sure you stop the access
    if url.startAccessingSecurityScopedResource() {
        url.stopAccessingSecurityScopedResource()
    }
}