NSURLSession使用绑定流上传后台文件 [英] NSURLSession Background File Upload using Bound Streams
问题描述
我正在研究一个我们需要支持的项目:
- 使用
NSURLSession
来上传文件。 - 服务器需要使用
Content-Type:multipart / form-data
- 以前,我使用
NSURLConnection
和绑定的Stream对,如 Apple示例。 - 现在,我希望通过使用
uploadTaskWithStreamedRequest
:。 - 我已经编写了一个独立的iOS Sample +一个PHP服务器来验证我的概念。
,使用
NSURLSession(后台会话)
问题: 一切工作,如果应用程序停留在前台,但如果在上传期间,我按Home键,一段时间后上传失败,错误:
Domain = NSURLErrorDomain Code = -997与后台传输服务器失去连接ice
在上传失败之前,写/生成器流的 NSStreamEventEndEncountered
遇到。
注意:我知道解决方法,我可以将整个HTTP Post主体写入临时文件并使用 NSURLSession的
文件上传API。但是,如果我可以做到这一点,以上是更合适的。
问题:有人可以猜测上传失败的可能原因是什么?
示例代码:我上传了iOS示例代码+ PHP服务器代码。这里是代码
谢谢!
您无法使用后台配置上传流式传输任务。我只在两种情况下成功上传数据:
$ b $ ol
History:
I am working on a project for which we need to support:
- Background Upload of files using
NSURLSession
. - The server expects file to be uploaded using
Content-Type: multipart/form-data
- Previously, I was using
NSURLConnection
with bound pair of Streams as depicted in this Apple Sample. - Now, I wish to follow similar approach with
NSURLSession(Background Session)
by usinguploadTaskWithStreamedRequest
:. - I have written a small stand-alone iOS Sample + a PHP server to validate my concept.
Problem: Everything works if app stays in foreground, but if during upload I press the home key, the upload fails after some time with error:
Domain=NSURLErrorDomain Code=-997 "Lost connection to background transfer service"
Also a little before the upload fails the Write/Producer Stream's NSStreamEventEndEncountered
is encountered.
Note: I know the work-around where I can write whole HTTP Post body to a temp file and use NSURLSession's
file upload API instead. But above is more appropriate if I can make it work.
Question: Can anyone guess what could be possible reason for the upload getting failed?
Sample Code: I have uploaded the iOS Sample Code + PHP Server Code to drop box. Here is the CODE
Thanks!
You can't upload streamed tasks using Background Configuration. I successfully upload data only in two cases:
- Download task with data stored in request body.
- Upload task from file. In that case you will not receive response body.
这篇关于NSURLSession使用绑定流上传后台文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!