【问题标题】:How to Upload video files in background?如何在后台上传视频文件?
【发布时间】:2016-10-11 18:38:59
【问题描述】:

我正在做一个应用程序,我需要上传从 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) in
    print("\((progress))")
 }

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

谁能分享一个真正有效的sn-p。正如我在谷歌上搜索的那样,NSURLSession.uploadTaskWithStreamedRequest 上的基本教程非常少,而且我尝试过的所有教程都不适用于 swift 2.2

我正在使用 Xcode 7.3 Swift 2.2

我知道的点:

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

  2. 要进行后台文件传输,我必须在Target->Capabilities -> Background Modes -> Background fetch

  3. 中启用它们
  4. 必须使用NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("") 设置会话管理器。但我不知道为什么以及在哪里使用该标识符。

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

【问题讨论】:

    标签: ios swift afnetworking nsurlsession


    【解决方案1】:

    我通过在 DispatchQueue Background queue 中调用上传函数来修复它

    DispatchQueue.global(qos: .background).async { upload() }
    

    【讨论】:

      猜你喜欢
      • 2016-02-05
      • 1970-01-01
      • 2016-08-13
      • 2020-06-27
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多