如何在后台上传PHAssets

时间:2017-01-17 12:13:45

标签: ios objective-c afnetworking

在Objective-C中我想在后台将所有PHAssets(图像和视频)上传到我的服务器。请问我能告诉我怎么做?

1 个答案:

答案 0 :(得分:1)

let mPhasset : PHAsset = PHAsset()
if mPhasset.mediaType == .image {
    let options: PHContentEditingInputRequestOptions = PHContentEditingInputRequestOptions()
    options.canHandleAdjustmentData = {(adjustmeta: PHAdjustmentData) -> Bool in
        return true
    }
    mPhasset.requestContentEditingInput(with: options, completionHandler: {(contentEditingInput: PHContentEditingInput?, info: [AnyHashable: Any]) -> Void in
        if let url = contentEditingInput?.fullSizeImageURL {
            // IMPORTANT
            // this url avaiable only in this block
            // we can't perform async operation in bg
            // cause access will expired

            // Now you can copy using FileManager
            // and after this upload copied file
        }
    })

    // Alternative

    let imageManager = PHCachingImageManager()
    let opt = PHImageRequestOptions()
    opt.resizeMode = .exact
    opt.deliveryMode = .highQualityFormat

    imageManager.requestImage(for: mPhasset,
                              targetSize: CGSize(width: mPhasset.pixelWidth, height: mPhasset.pixelHeight),
                              contentMode: .aspectFill,
                              options: opt,
                              resultHandler:
        { (image: UIImage?, _) in
        // now you can go to background and do whatever you want
        // benefit that you don't need to copy file in main thread
        // which can lag your app
        // disadvantage of this method: we load image in memory
    })

} else if mPhasset.mediaType == .video {
    let options: PHVideoRequestOptions = PHVideoRequestOptions()
    options.version = .current

    PHImageManager.default().requestExportSession(forVideo: mPhasset, options: options, exportPreset: AVAssetExportPresetHighestQuality, resultHandler: { (session, info) in
        // if we just request video url asset and try upload to server
        // we will have problems with slow mo videos
        // also we will be on the main thread and access for video will expire, if we go to background
        // + size of video is very huge

        guard let session = session else { return }
        session.outputURL = URL(fileURLWithPath: "our output path")
        session.outputFileType = AVFileTypeQuickTimeMovie
        session.shouldOptimizeForNetworkUse = true
        session.exportAsynchronously {
            if (session.status == .completed) {
                // success
            } else {
            }
        }
    })
}