iOS Photo Library读访问权限

时间:2015-02-08 18:55:57

标签: ios photokit

用户授权我们访问他的相机胶卷后。我们想从我们的应用程序中获取数据并将其上传到我们的服务。 有没有办法从文件中访问视频数据?打开视频文件的唯一方法是创建AVAsset。但这对我来说还不够。

我知道了

func requestExportSessionForVideo(_ asset: PHAsset!,
                      options options: PHVideoRequestOptions!,
                 exportPreset exportPreset: String!,
                resultHandler resultHandler: ((AVAssetExportSession!,
                    [NSObject : AnyObject]!) -> Void)!) -> PHImageRequestID

但在我的情况下,我只是想将视频上传到我不想做的服务:

  1. 首先通过导出到我的本地应用数据来复制视频
  2. 然后将该数据发送到我们的服务。
  3. 删除数据。
  4. 上述方法使用了大量额外的空间和时间,用户使用完整的16GB iPhone无法正常工作。

    好的,这是我到目前为止使用URL

    尝试的
    var anAcces = sourceURL?.startAccessingSecurityScopedResource
    
    if !NSFileManager.defaultManager().fileExistsAtPath(sourceURL!.path!) {
        NSLog("not exist")
    }
    
    var aFileCoordinator = NSFileCoordinator(filePresenter:nil)
    var anError: NSError?
    
    aFileCoordinator.coordinateReadingItemAtURL(sourceURL!, options:.ForUploading, error:&anError, byAccessor:  { (newURL: NSURL!) -> Void in
        var data = NSData(contentsOfURL: newURL)
        })
    if let unError = anError {
        NSLog("Error \(unError)")
    }
    
    sourceURL?.stopAccessingSecurityScopedResource
    

    记录以下内容:

    2015-02-08 16:20:01.947 Cameo[15706:2288691] not exist
    2015-02-08 16:20:01.991 Cameo[15706:2288691] Error Error Domain=NSCocoaErrorDomain Code=257 "The operation couldn’t be completed. (Cocoa error 257.)" UserInfo=0x170876480 {NSURL=file:///var/mobile/Media/DCIM/100APPLE/IMG_0155.MOV, NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0155.MOV, NSUnderlyingError=0x17005a9a0 "The operation couldn’t be completed. Operation not permitted"}
    

2 个答案:

答案 0 :(得分:1)

感谢保罗的建议我明白了:

您必须在该块中创建一个PHImageManager requestAVAssetForVideo会话,您可以访问该文件并从该URL读取其数据。

    let imageManager = PHImageManager.defaultManager()
    let videoRequestOptions = PHVideoRequestOptions()

    videoRequestOptions.deliveryMode = .HighQualityFormat
    videoRequestOptions.version = .Current
    videoRequestOptions.networkAccessAllowed = true
    videoRequestOptions.progressHandler = { (progress: Double, error: NSError!, stop: UnsafeMutablePointer<ObjCBool>, [NSObject : AnyObject]!) -> Void in

        NSLog("Progress: %@", progress.description)
    }

    videoRequestOptions.progressHandler = { (progress: Double, error: NSError!, stop: UnsafeMutablePointer<ObjCBool>, [NSObject : AnyObject]!) -> Void in

        NSLog("Progress: %@", progress.description)
    }

    imageManager.requestAVAssetForVideo(nextAsset, options: videoRequestOptions, resultHandler: { (avAsset: AVAsset!, avAudioMix: AVAudioMix!, info: [NSObject : AnyObject]!) -> Void in

        if let nextURLAsset = avAsset as? AVURLAsset {

            let sourceURL = nextURLAsset.URL

            if NSFileManager.defaultManager().fileExistsAtPath(sourceURL.path!) {
                NSLog("exist file")
            }

            var data = NSData(contentsOfURL: sourceURL)

            if let aData = data {
                NSLog("length : <\(aData.length)")
            }
            else {
                NSLog("no data read.")
            }
        }
    }

答案 1 :(得分:1)

关于问题:

Failed to issue sandbox extension for file file:///var/mobile/Media/DCIM/100APPLE/IMG_0730.MOV, errno = 1

我解决这个问题的方法是创建一个临时路径,我可以访问媒体文件:

  Future<void> loadAssets() async {
    List<Asset> resultList = <Asset>[];
    String error = 'No Error Detected';
    final temp = await Directory.systemTemp.create();
    List<File> imagesFileList = [];

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 300,
        enableCamera: true,
        selectedAssets: imagesAssetsList,
        cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
        materialOptions: MaterialOptions(
          actionBarColor: "#abcdef",
          actionBarTitle: "Example App",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
    }
    if (!mounted) return;

    for (int i = 0; i < resultList.length; i++) {
      final data = await resultList[i].getByteData();
      imagesFileList.add(await File('${temp.path}/img$i').writeAsBytes(
          data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes)));
      print('pathnew: ${imagesFileList[i].path}');
      await uploadFileToStorage(imagesFileList[i].path);
    }

    setState(() {
      imagesAssetsList = resultList;

      _error = error;
    });
  }

我希望它会奏效!