uploadFaskWithRequest后台会话来自文件崩溃

时间:2016-05-20 07:44:49

标签: ios swift

我正在使用swift 2编写应用程序,我需要在后台会话中在我的服务器上上传照片和视频。出于这个原因,我写了这段代码:

        let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(SessionProperties.identifier)
        //let configuration = NSURLSessionConfiguration.defaultSessionConfiguration();

        let queue = NSOperationQueue.mainQueue()

        // To limit to 1 upload at a time

        queue.maxConcurrentOperationCount = 1

        let backgroundSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: queue)

        for postingFile in postingFileList {

            let request = NSMutableURLRequest(URL: NSURL(string: NetworkUtil().serverUrl+"/upload/upload/v1.0/events/\(postingFile.event.id)/files/\(postingFile.file.id)?frag-start=0&frag-size=\(postingFile.fileSize)")!)

            request.HTTPMethod = "POST"

            request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")

            let uploadTask = backgroundSession.uploadTaskWithRequest(request, fromFile: postingFile.url)

            //let uploadTask = backgroundSession.uploadTaskWithRequest(request, fromFile: postingFile.url, completionHandler: { (NSData, NSURLResponse, NSError) in
            //    print("completion handler")
            //})

            uploadTask.resume()
        }

此代码在第<:p>行崩溃

            let uploadTask = backgroundSession.uploadTaskWithRequest(request, fromFile: postingFile.url)

它说:

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'无法读取文件:///var/mobile/Media/DCIM/100APPLE/IMG_0361.JPG'

如果我不使用后台会话,请改用此配置:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration();

没有崩溃,上传完成。

您是否知道使用文件进行后台会话会发生什么?

1 个答案:

答案 0 :(得分:1)

这可能是许可问题。您正尝试从后台进程访问非沙盒文件URL。尝试将文件本地移动到沙箱目录,然后在后台上传。