Skip to content

Convert ALAsset to NSInputStream for HTTPBodyStream of NSURLMutableRequest in case of out of memory

Notifications You must be signed in to change notification settings

luowenxing/ALAssetToNSInputStream

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 

Repository files navigation

ALAssetToNSInputStream

When using NSURLRequest to upload a large file,we prefer to set HTTPBodyStream instead of HTTPBody in case of out of memory error if the file server support stream transfer.

If the large file is inside your sandbox,it would be easy to use initializer of NSURL.But if you choose a large video via ALAssetsLibrary and get a ALAsset instance,there is no direct way to convert ALAsset to NSInputStream.

Now you just need to add a single ALAssetToNSInputStream.swift to your project and you can easily get it through.

Usage

  • Add ALAssetToNSInputStream.swift to your project
  • Get NSInputStream in either methods.
//assuming assetUrl is the `NSURL` of `ALAsset`
let inpurStream1 = NSInputStream.inputStreamWithAssetURL(assetUrl)
let inputStream2 = ALAssetNSInputStream(URL: assetUrl)

Note

inputStream1 is implemented by CFCreateBounderPair which use two stream to transfer data from one side to the other side,and will not change the behavior of NSInputStream.It's may be more safer.

inputStream2 is implemented by inheriting NSInputStream which completely overrides super methods,and changes the behavoir of NSInputStream.

  • Set HTTPBodyStream of NSMutableURLRequest to NSInputStream you got
  • Start your network request by NSURLConnection or NSURLSession

About Multipart Form Stream

If your server is designed for web application and only accept file using multipart/formdata,you can work around with PKMultipartInputStream.

let stream = PKMultipartInputStream()
let assetStream = ALAssetNSInputStream(URL: assetUrl)
let rept = assetStream.rept
stream.addPartWithName("fieldName", filename: rept.filename(), stream: assetStream, streamLength:UInt(rept.size()))

Then you got a NSInputStream containing ALAsset file with Content-Type of Multipart/formdata

Reference

iOS Developer Library

For large blocks of constructed data, call CFStreamCreateBoundPair to create a pair of streams, then call the setHTTPBodyStream: method to tell NSMutableURLRequest to use one of those streams as the source for its body content. By writing into the other stream, you can send the data a piece at a time.

ios-how-to-upload-a-large-asset-file-into-sever-by-streaming

About

Convert ALAsset to NSInputStream for HTTPBodyStream of NSURLMutableRequest in case of out of memory

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages