如何在Xcode(Swift)上将视频从相机胶卷添加到应用程序

时间:2017-05-06 00:57:00

标签: ios swift xcode video camera

我希望用户能够从相机胶卷导入视频,进行编辑,然后将视频保存到相机胶卷。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

嗯,首先你需要问这样的用户权限:

AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { response in
    if response {
        //access granted
    } else {

    }
}

//Photos
let photos = PHPhotoLibrary.authorizationStatus()
if photos == .notDetermined {
    PHPhotoLibrary.requestAuthorization({status in
        if status == .authorized{
            ...
        } else {}
    })
}

然后你需要在plist文件中提供一些关于你想要它的描述,如下所示:

<key>NSCameraUsageDescription</key>
<string>You can take photos</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>You can select photos to attach it on this app.</string>

关于编辑视频,这是一个非常主观的主题。你需要做些什么改变?根据你想做的事情,这可能会非常复杂。

稍后保存到相机胶卷,我得到一个代码示例,下载文件并将其保存到相机胶卷:

import AssetsLibrary

...
...

func downloadVideoToCameraRoll() {

// Local variable pointing to the local file path for the downloaded video
var localFileUrl: String?

// A closure for generating the local file path for the downloaded video. This will be pointing to the Documents directory with a unique UDID file name.
let destination: (NSURL, NSHTTPURLResponse) -> (NSURL) = {
    (temporaryURL, response) in

    if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
        let finalPath = directoryURL.URLByAppendingPathComponent("\(NSUUID()).\(response.suggestedFilename!)")
        localFileUrl = finalPath.absoluteString
        return finalPath
    }

    return temporaryURL
}

// The media post which should be downloaded
let postURL = NSURL(string: "https://api.instagram.com/v1/media/" + "952201134785549382_250131908" + "?access_token=" + InstagramEngine.sharedEngine().accessToken)!

// Then some magic happens that turns the postURL into the videoURL, which is the actual url of the video media:
let videoURL = NSURL(string: "https://scontent.cdninstagram.com/hphotos-xfp1/t50.2886-16/11104555_1603400416544760_416259564_s.mp4")!

// Download starts
let request = Alamofire.download(.GET, videoURL, destination)

// Completion handler for the download
request.response { (request, response, data, error) -> Void in
    if let path = localFileUrl {
        let isVideoCompatible = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path)
        println("bool: \(isVideoCompatible)") // This logs out "bool: false"

        let library = ALAssetsLibrary()

        library.writeVideoAtPathToSavedPhotosAlbum(NSURL(string: path), completionBlock: { (url, error) -> Void in
            // Done! Go check your camera roll
        })
    }
}
}
祝你好运!