Using the Firebase repository putFile () method causes the file "fileName" cannot be opened.

Here are two ways I tried to upload a file:

1.

getURLOfPhoto(assetURL: imagesDictionary[String(whichProfileImage)]! , completionHandler: { (responseURL) in          
                                    FIRStorage.storage().reference().putFile(responseURL as! URL)
                            })

2.

  let assets = PHAsset.fetchAssets(withALAssetURLs: [imagesDictionary[String(whichProfileImage)] as! URL], options: nil)
            let asset = assets.firstObject
            asset?.requestContentEditingInput(with: nil, completionHandler: { (contentEditingInput, info) in
                let imageFile = contentEditingInput?.fullSizeImageURL?

                FIRStorage.storage().reference().child("test").putFile(imageFile!, metadata: nil) { (metadata, error) in
                        if let error = error {                   
                            return
                        }   
                }
            })

I get this error:

 Body file is unreachable: /var/mobile/Media/DCIM/100APPLE/picture.JPG        
    Error Domain=NSCocoaErrorDomain Code=257 "The file "picture.JPG" couldn’t be opened because you don’t have permission to view it."     
        UserInfo={NSURL=file:///var/mobile/Media/DCIM/100APPLE/picture.JPG, NSFilePath=/var/mobile/Media/DCIM/100APPLE/picture.JPG,     
    NSUnderlyingError=0x15da49a0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

It seems that the URL was successfully restored, and the error only occurs when the method is called putFile().

Does anyone know how to fix this error or another way to upload a file (not a Data object) to Firebase storage?

Thanks in advance

+4
source share
3 answers

Firebase Storage URL- , PHAsset, (, , ) - , iPhone. , , Firebase Storage API, , URL- putFile().

, imagePickerController():

do {
   let documentsURL = FileManager.default().urlsForDirectory(.documentDirectory,
                                                                          inDomains: .userDomainMask)[0]
   let fileURL = try documentsURL.appendingPathComponent("fileName.jpg")

   let image = info[UIImagePickerControllerOriginalImage]

   try UIImageJPEGRepresentation(image as! UIImage,1.0)?.write(to: fileURL, options: [])

                    FIRStorage.storage().reference().child("exampleLocation")
                        .putFile(fileURL, metadata: nil) { (metadata, error) in
    if let error = error {
                                print("Error uploading: \(error.description)")
                                return
                            }
                       }                
                 }
         catch {
            print("error is ", error)
        }
+4

, - ( ).

Documents/ tmp/ https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html

, , . (, data file , , ):

  // pragma mark - UIImagePickerDelegate overrides
  func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    // Get local image
    guard let image: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
    let imageData = UIImagePNGRepresentation(image)!

    // Get a reference to the location where we'll store our photos
    let photosRef = storage.reference().child("chat_photos")

    // Get a reference to store the file at chat_photos/<FILENAME>
    let photoRef = photosRef.child("\(NSUUID().UUIDString).png")

    // Upload file to Firebase Storage
    let metadata = FIRStorageMetadata()
    metadata.contentType = "image/png"
    photoRef.putData(imageData, metadata: metadata).observeStatus(.Success) { (snapshot) in
      // When the image has successfully uploaded, we get it download URL
      let text = snapshot.metadata?.downloadURL()?.absoluteString
    }

    // Clean up picker
    dismissViewControllerAnimated(true, completion: nil)
  }
+1

@ , , . , . :

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    guard let image: UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage else { return }
    let profileImageName = "profileImageName.png"
    let imageData = UIImagePNGRepresentation(image)!
    let filePath = "\(FIRAuth.auth()!.currentUser!.uid)/\(Int(NSDate.timeIntervalSinceReferenceDate() * 1000))"

    let photoStorageRef = FIRStorage.storage().reference().child(filePath)
    let photoRef = photoStorageRef.child("\(profileImageName)")

    let metadata = FIRStorageMetadata()
    metadata.contentType = "image/png"

    photoRef.putData(imageData, metadata: metadata) { metadata, error in
        if let error = error {
            print("Error uploading:\(error.localizedDescription)")
            return
        } else {
            guard let downloadURL = metadata!.downloadURL() else { return }
            guard let downloadURLString = metadata!.downloadURL()?.absoluteString else { return }

            //do what I need to do with downloadURL
            //do what I need to do with downloadURLString
        }
    }

, - !

0

Source: https://habr.com/ru/post/1648169/


All Articles