问题
I am using Alamofire to upload assets (image/video) as multipart form data. It works fine for file sizes below 300MB (app). When I try to upload a file greater than 300MB, app crashes.
if let video = self.avPlayerItem?.asset as? AVURLAsset {
if let assetData = NSData(contentsOfURL: video.URL) {
multipartFormData.appendBodyPart(data: assetData, name: "file", fileName: "video", mimeType: "video/mp4") // Execution stops here
}
}
I also get the below message from Xcode
How would I support uploading huge sized videos using Alamofire?
回答1:
Use Stream to upload instead of converting file to NSData which lead to memory problem and occur crash while uploading huge files. sample code
if let imageUrl = info[UIImagePickerControllerReferenceURL] as? NSURL{
let assetLibrary = ALAssetsLibrary()
assetLibrary.assetForURL(imageUrl , resultBlock: { (asset: ALAsset!) -> Void in
if let actualAsset = asset as ALAsset? {
let assetRep: ALAssetRepresentation = actualAsset.defaultRepresentation()
let size = assetRep.size()
let stream = NSInputStream(URL: assetRep.url())
Alamofire.upload(
.POST,
"SERVER_URL",
headers: [:],
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(stream: stream!, length: UInt64(size), name: "fileparameter", fileName: "fileName", mimeType: "video/mp4")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
dispatch_async(dispatch_get_main_queue()) {
let percent = (Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
print(percent)
}
}
upload.validate()
upload.responseJSON { response in
print(response);
}
case .Failure(let encodingError):
print(encodingError)
let error = NSError(domain: "", code: 404, userInfo: [NSLocalizedDescriptionKey: "Image Uploading Failed. Please try again."])
let result = Result<AnyObject, NSError>.Failure(error)
let response = Response(request: nil, response: nil, data: nil, result: result)
print(response);
}
}
)
}
}, failureBlock: { (error) -> Void in
})
}
来源:https://stackoverflow.com/questions/40398201/alamofire-upload-huge-file