如何在后台上传视频文件?

时间:2016-06-10 17:42:11

标签: ios swift afnetworking nsurlsession

我正在做一个应用,我需要上传从iPhone相机拍摄的视频并将其上传到服务器。当应用程序处于前台时,视频会上传但我不知道在应用程序处于非活动状态时如何在后台运行。我使用AFNetworking来进行多部分数据上传。这是我试过的代码

var task:NSURLSessionUploadTask!
let FILEPICKER_BASE_URL = "My server Url"
var isUploading : Bool = false
var videoPath : String!
func upload(dictMain: NSMutableDictionary)
{
    isUploading = true
    let uuid =  NSUUID().UUIDString + "-" + (getUserId().description)
    let request = AFHTTPRequestSerializer().multipartFormRequestWithMethod("POST", URLString: FILEPICKER_BASE_URL, parameters: nil, constructingBodyWithBlock: { (fromData) in

        do {
            try fromData.appendPartWithFileURL(NSURL(fileURLWithPath: videoPath) , name: "fileUpload", fileName: uuid, mimeType: "video/quicktime")
        }catch{
            print(error)
        }
        }, error: nil)

    let manager:AFURLSessionManager = AFURLSessionManager(sessionConfiguration: NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("Your video is uploading"));

    task = manager.uploadTaskWithStreamedRequest(request, progress: nil , completionHandler: { (response, responseObject, error) in
            NSLog("Resposne Object: \(responseObject)")
            post(dictMain,response: responseObject!)
    })
    task.resume()    
}

此外,我不知道如何知道我的上传进度。我尝试在progress参数

中使用以下块
 { (progress) in
    print("\((progress))")
 }

但它不起作用编译器显示错误 Cannot convert value of type '(_) -> _' to expected argument type 'AutoreleasingUnsafeMutablePointer<NSProgress?>' (aka 'AutoreleasingUnsafeMutablePointer<Optional<NSProgress>>')

任何人都可以共享一个真正有用的代码段。正如我用Google搜索的那样,NSURLSession.uploadTaskWithStreamedRequest上的基本教程非常少,我尝试过的所有教程都没有在swift 2.2上运行

我正在使用Xcode 7.3 Swift 2.2

  

我知道的要点:

  1. 后台上传仅适用于文件路径,而不适用于NSData。所以我从UIImagePickerController函数func video(videoPath: NSString, didFinishSavingWithError error: NSError?, contextInfo info: AnyObject)

  2. 中获取了视频网址路径
  3. 要进行后台文件传输,我必须在Target - &gt; Capabilities - &gt;中启用它们。 Background Modes - &gt; Background fetch

  4. 必须使用NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("")设置会话管理器。但我不知道该标识符的使用原因和位置。

  5. 我知道这是一篇很长的帖子。但如果得到回答,这肯定会对许多开发人员有所帮助。

1 个答案:

答案 0 :(得分:0)

我通过调用¨

中的上载函数来修复它
DispatchQueue Background queue
相关问题