I am uploading image and video to QuickBlox. My upload is successful but when i download the following scenarios occour:
1) In case of image i am able to download image and show (No issues in this)
2) My question is about video with below points
a) I am able upload video successfully
b) How would i be able to recognize the extension of video from server? I need sample code for uploading and downloading video from the QuickBlox. As if i upload .mov file then what should be the filetype and what should be in case of .mp4 and so on. And when i download the file how would i know the correct extension for the file and then how to get the correct file from the server and save it.
When uploading a video, set the type to "video" in the attachment and the corresponding content type, for example "video/mp4":
QBRequest.uploadFile(with: localVideoUrl, fileName: nameVideo, contentType: "video/mp4", isPublic: true,
successBlock: { (response: QBResponse, uploadedBlob: QBCBlob) -> Void in
let attachment = QBChatAttachment()
attachment.id = uploadedBlob.uid
attachment.name = uploadedBlob.name
attachment.type = "video"
attachment["size"] = "\(uploadedBlob.size)"
// send message with attachment
}, statusBlock: { (request : QBRequest?, status : QBRequestStatus?) -> Void in
let progress = CGFloat(Float(status.percentOfCompletion))
// show progress
}
}) { (response : QBResponse) -> Void in
//error handler
}
When you receive a message with attachment and attachment type is "videoā€¯, refer to this example:
let attachment = message.attachments?.first
if attachment.type == "video" {
QBRequest.downloadFile(withUID: attachment.id, successBlock: { (response: QBResponse, fileData: Data) in
let fileData = fileData as NSData
let fileName = ID + "_" + attachment.name
let filePath = NSTemporaryDirectory() + fileName
let fileURL = URL(fileURLWithPath: filePath)
if fileData.write(to: fileURL, atomically: true) == true {
//do what you need with the video - cache, save, play, etc.
} else {
print("failure write")
}
}, statusBlock: { (request: QBRequest, status: QBRequestStatus?) in
let progress = CGFloat(status.percentOfCompletion)
//show progress
}, errorBlock: { (response: QBResponse) in
//error handler
})
}
Related
I receive a String from a WebApi representing a Base64 PDF.
I implement this method to convert that Base64 String into a PDF and save it on documents.
/**
Saves Base64 to PDF
taken from: https://stackoverflow.com/a/40164036/15860448
*/
func saveBase64StringToPDF(_ base64String: String, fileName: String) -> URL? {
Logger.log(.warning, "Saving PDF...")
guard
var documentsURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last,
let convertedData = Data(base64Encoded: base64String)
else {
//handle error when getting documents URL
Logger.log(.error, "Error creating URL of PDF")
return nil
}
//name your file however you prefer
documentsURL.appendPathComponent("\(fileName).pdf")
do {
try convertedData.write(to: documentsURL)
//if you want to get a quick output of where your
//file was saved from the simulator on your machine
//just print the documentsURL and go there in Finder
Logger.log(.success, "Saved \(fileName) in \(documentsURL)")
return documentsURL
} catch {
//handle write error here
Logger.log(.success, "Error saving")
return nil
}
}
Now my goal is to open that File using the URL returned by saveBase64StringToPDF()
I have this method:
/**
Opens file
*/
func openFile(path: URL) {
if UIApplication.shared.canOpenURL(path) {
UIApplication.shared.open(path, options: [:], completionHandler: nil)
}
else{
Logger.log(.error, "Error opening URL: \(path)")
}
}
But I keep getting this error:
2022-03-03 14:34:39.271338+0100 LotoUp[7021:2647489] -canOpenURL: failed for URL: "file:///var/mobile/Containers/Data/Application/7D2DC4E8-90A7-4741-A730-CE039894FC88/Documents/liquidacion_2022-7_148.pdf" - error: "This app is not allowed to query for scheme file"
Any help?
I'm using alamofire5 beta and I can't find the encodingResult that was used in previous versions.
This is my code function:
static func postComplexPictures(complexId: String, pictures: [UIImage], completion:#escaping (DataResponse<Data?>) -> Void) {
let url = K.ProductionServer.baseURL + "/api/v1/complex/" + complexId + "/pictures"
let token: String = UserDefaults.standard.string(forKey: "Token") ?? ""
let bearerToken: String = "Bearer " + token
let bundleId: String = Bundle.footballNow.bundleIdentifier!
let headers: HTTPHeaders = [HTTPHeaderField.authentication.rawValue: bearerToken,
HTTPHeaderField.contentType.rawValue: ContentType.multipart.rawValue,
HTTPHeaderField.bundleIdentifier.rawValue: bundleId]
AF.upload(multipartFormData: { (multipartFormData) in
for image in pictures {
if let imageData = UIImageJPEGRepresentation(image, 0.5) {
multipartFormData.append(imageData, withName: "pictures[\(index)]", fileName: "picture", mimeType: "image/jpeg")
}
}
}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers).response(completionHandler: completion)
}
The .response actually calls my block, but it returns too quick for the images to be uploaded and I don't have a reference to the uploading status of the images.
Any thoughts?
Thanks!
I'm happy to say that there is no encoding result in Alamofire 5! Instead, failures in multipart encoding, and the async work required to encode it, are now part of the same request path as everything else. So you'll get any errors in your response calls, just like any other request. So if your request is finishing quickly, check the error, as the multipart encoding may have failed.
I'm currently developing an application in swift 3 for a school project that requires uploading files to google drive .
The upload is currently working , but i need to inform users with an upload bar.
Here the current code
let folderId: String = folders[indexPath.row].folderId
let metadata = GTLRDrive_File.init()
metadata.name = "Ruin.mp3"
// metadata.mimeType = "application/vnd.google-apps.photo"
metadata.parents = [folderId]
guard let filePath = Bundle.main.path(forResource: "Ruin", ofType: "mp3") else {
return
}
guard let fileData = FileManager.default.contents(atPath: filePath) else {
return
}
let uploadParameters = GTLRUploadParameters(data: fileData , mimeType: "audio/mpeg")
uploadParameters.shouldUploadWithSingleRequest = true
let query = GTLRDriveQuery_FilesCreate.query(withObject: metadata, uploadParameters: uploadParameters)
query.fields = "id"
self.service.executeQuery(query, completionHandler: {(ticket:GTLRServiceTicket, object:Any?, error:Error?) in
if error == nil {
// print("File ID \(files.identifier)")
}
else {
print("An error occurred: \(error)")
}
})
Thanx in advance
I have a problem getting an image from filesystem. On iOS works fine.
First of all, I save a remote image in the filesystem with this function:
img.imagen = url from the remote image (e.g. http://onesite.es/img2.jpeg)
function descargarImagen(img, callback){
var path = img.imagen;
var filename = path.split("/").pop();
var xhr = Titanium.Network.createHTTPClient({
onload: function() {
// first, grab a "handle" to the file where you'll store the downloaded data
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, filename);
f.write(this.responseData); // write to the file
Ti.API.debug("-- Imagen guardada: " + f.nativePath);
callback({path: f.nativePath});
},
timeout: 10000
});
xhr.open('GET', path);
xhr.send();
}
Now, I want to share this image creating an Android Intent:
args.image = f.nativePath(in the previous function)
var intent = null;
var intentType = null;
intent = Ti.Android.createIntent({
action: Ti.Android.ACTION_SEND
});
// add text status
if (args.status){
intent.putExtra(Ti.Android.EXTRA_TEXT, args.status);
}
// change type according to the content
if (args.image){
intent.type = "image/*";
intent.putExtraUri(Ti.Android.EXTRA_STREAM, args.image);
}else{
intent.type = "text/plain";
intent.addCategory(Ti.Android.CATEGORY_DEFAULT);
}
// launch intent
Ti.Android.currentActivity.startActivity(Ti.Android.createIntentChooser(intent, args.androidDialogTitle));
What I'm doing wrong?
func downloadPDF() {
// Running operations that takes a long time in a background thread is recommended
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
// Get the PDF data from the URL
let url = self.webview.request?.URL
let pdfURL = url?.absoluteString
let pdfData = NSData(contentsOfURL: NSURL(string: pdfURL!)!)!
// Store the data locally as a PDF file in the Documents directory
let documentsDirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String
localPdfPath = documentsDirPath.stringByAppendingPathComponent(pdfURL!.lastPathComponent)
pdfData.writeToFile(localPdfPath, atomically: true)
// UI related stuff should be called in the main thread.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.openIniBooks()
self.stopActivityIndicator()
})
})
}
Save PDF file to iBooks was working fine until upgrade to xCode7. Now getting an error:
Downcast from String? to String only unwraps optionals... for this line:
let documentsDirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String
Not sure how to fix that. Tried:
let documentsDirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
But got new error. Any help would be appreciated.
Try this:
let documentsDirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String!