How to get image from NSOutputStream in Objective-C - ios

I am using twilio chat SDK, in that I am doing store and retrieve the image.
So to retrieve the image from twilio I am getting NSOutputStream, And I don't know that how to convert NSOutputStream to image. Please see the below code which provided by twilio and give me some suggestions.
chatCell.message = message.body;
if (message.hasMedia) {
NSLog(#"mediaFilename: %# (optional)", message.mediaFilename);
NSLog(#"mediaSize: %lu", (unsigned long)message.mediaSize);
// Set up output stream for media content
NSString *tempFilename = [NSTemporaryDirectory() stringByAppendingPathComponent:message.mediaFilename ? #"file.dat" : message.mediaFilename];
NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:tempFilename append:NO];
// Request the start of the download
[message getMediaWithOutputStream:outputStream
onStarted:^{
// Called when download of media begins.
} onProgress:^(NSUInteger bytes) {
// Called as download progresses, with the current byte count.
} onCompleted:^(NSString * _Nonnull mediaSid) {
// Called when download is completed, with the new mediaSid if successful.
// Full failure details will be provided through the completion block below.
} completion:^(TCHResult * _Nonnull result) {
if (!result.isSuccessful) {
NSLog(#"Download failed: %#", result.error);
} else {
NSLog(#"Download successful");
NSLog(#"%#",message.body);
}
}];
}
I am not sure how to get an image after download complete successful. Please help me to fix this.
Thanks in advance.

Related

iOS objC upload file to firebase not happening

I need to upload a file to firebase, firebase account is set, iOS project is connecting...
The file exists, and I check for file size before sending...
when I try the upload the process starts, but I get the error:
Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown error occurred, please check the server response
This is the path for the file:
/var/mobile/Containers/Data/PluginKitPlugin/A14B0460-06E7-4EC0-80CE-9C27B5B70BC2/Documents/img.JPG
My doubt is if I have "riversRef" property correctly set?... What is missing?
- (void)uploadFileTest:(NSURL*)url {
// reference
FIRStorage * storage = [FIRStorage storage];
// Create a root reference
FIRStorageReference *storageRef = [storage reference];
FIRStorageReference *riversRef = [storageRef child:#"images/rios.jpg"]; // is this correct?
FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
metadata.contentType = #"image/jpeg";
NSLog(#"storageRef: %#", storageRef);
NSLog(#"url path: %#", [url path]);
NSLog(#"metadata : %#", metadata);
//object size?
if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]]){
long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:url.absoluteString error:nil][NSFileSize] longLongValue];
NSLog(#"sik: %lld", fileSize);
}else{
NSLog(#"nanais");
}
NSURL *curaul = [NSURL fileURLWithPath:[url path]];
// Upload file and metadata to the object 'images/rios.jpg'
FIRStorageUploadTask *uploadTask = [riversRef putFile:curaul metadata:metadata];
// Listen for state changes, errors, and completion of the upload.
[uploadTask observeStatus:FIRStorageTaskStatusResume handler:^(FIRStorageTaskSnapshot *snapshot) {
// Upload resumed, also fires when the upload starts
NSLog(#"upload started");
}];
[uploadTask observeStatus:FIRStorageTaskStatusPause handler:^(FIRStorageTaskSnapshot *snapshot) {
// Upload paused
NSLog(#"paused");
}];
[uploadTask observeStatus:FIRStorageTaskStatusProgress handler:^(FIRStorageTaskSnapshot *snapshot) {
// Upload reported progress
double percentComplete = 100.0 * (snapshot.progress.completedUnitCount) / (snapshot.progress.totalUnitCount);
NSLog(#"percentComplete :: %f", percentComplete);
}];
[uploadTask observeStatus:FIRStorageTaskStatusSuccess handler:^(FIRStorageTaskSnapshot *snapshot) {
// Upload completed successfully
NSLog(#"successfully");
}];
// Errors only occur in the "Failure" case
[uploadTask observeStatus:FIRStorageTaskStatusFailure handler:^(FIRStorageTaskSnapshot *snapshot) {
NSLog(#"errore :: %#", snapshot.error.description);
if (snapshot.error != nil) {
switch (snapshot.error.code) {
case FIRStorageErrorCodeObjectNotFound:
// File doesn't exist
break;
case FIRStorageErrorCodeUnauthorized:
// User doesn't have permission to access file
break;
case FIRStorageErrorCodeCancelled:
// User canceled the upload
break;
/* ... */
case FIRStorageErrorCodeUnknown:
// Unknown error occurred, inspect the server response
break;
}
}
}];
}
Is the response to unknown error?
How to fix upload?, thanks

receive Data via BLE on IOS, Data is always old

I´m new in iOS Programming and i´m trying to receive Data from a BLE device. I´m able to connect to the device and send data to the device. The problem is receiving data from the BLE Device.
Im using this as BLE Base:
LGBluetooth
Problem:
#property (nonatomic,strong) NSString* recievedData; //data recieved from Peripheral
- (void)RecieveDataBLE:(LGPeripheral *)peripheral :(NSString*)Service_UUID :(NSString*)Characteristic_UUID {
//Function to read Data from BLE Device
[LGUtils readDataFromCharactUUID:Characteristic_UUID serviceUUID:Service_UUID
peripheral:peripheral
completion:^(NSData *data, NSError *error) {
NSLog(#"Data : %s Error : %#", (char *)[data bytes], error);
recievedData = [NSString stringWithUTF8String:[data bytes]];
}
- (IBAction)sendDOWN:(id)sender {
MessageLabel.hidden = NO;
[self RecieveDataBLE:mBuddy:SERVICE_UUID_DEVICE_INFORMATION:CHARACTERISTIC_UUID_MANUFACTURER];
MessageLabel.text = [NSString stringWithFormat:#"%#",recievedData]; //Output is always old!!
}
After the action sendDown is called, data should be read via the ReceiveDataBle function. This one will then process the data. The problem is, ReceiveDataBle is always too late, and does not receive the information immediately, but after a certain time. A callback function returns the data to ReceiveDataBle. So when the action SendDown is called the Data from the last call appears in the MessageLabel!!
The question is, how can I ensure that I have the newest data available, and not outdated data?
**You can use this type when show updated recievedData **
-(IBAction)sendDOWN:(id)sender
{
MessageLabel.hidden = NO;
[LGUtils readDataFromCharactUUID:Characteristic_UUID
serviceUUID:Service_UUID
peripheral:peripheral
completion:^(NSData *data, NSError *error) {
NSLog(#"Data : %s Error : %#", (char *)[data bytes], error);
recievedData = [NSString stringWithUTF8String:[data bytes]];
MessageLabel.text = [NSString stringWithFormat:#"%#",recievedData];
}
}

Using AWSS3TransferUtility to upload data on iOS

I've managed to successfully upload data using the AWS 2.0 SDK, however I'm having some trouble understanding the "re-wiring" of completion handlers that is meant to take place on resuming of the app.
What I believe I should be doing, is at comment 6, saving the upload task. Then if it reaches the completionHandler block, deleting it. However, if the app is terminated before this, I can look at my saved upload tasks in the block at comment 4. Any saved tasks would be "re-wired" to the completion handler.
For reference, imagine this code happening in an "Upload" class, and in a block, which is the "uploadSuccess()" code you see in the completionHandler.
For reference here is the blog that introduced the AWSS3TransferUtility, and here is its documentation.
Hopefully someone can guide me on this.
// 1. Get/Setup credentials
AWSCognitoCredentialsProvider *credentialsProvider = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1 identityPoolId:#"IdentityPoolId"];
AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:credentialsProvider];
AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;
// 2. Create AWSS3 Transfer blocks
AWSS3TransferUtilityUploadExpression *expression = [AWSS3TransferUtilityUploadExpression new];
expression.uploadProgress = ^(AWSS3TransferUtilityTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
dispatch_async(dispatch_get_main_queue(), ^{
// Do something e.g. Update a progress bar.
});
};
AWSS3TransferUtilityUploadCompletionHandlerBlock completionHandler = ^(AWSS3TransferUtilityUploadTask *task, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
// Do something e.g. Alert a user for transfer completion.
// On failed uploads, `error` contains the error object.
if (error) {
uploadSuccess(NO);
} else {
uploadSuccess(YES);
}
});
};
// 3. Create Transfer Utility
AWSS3TransferUtility *transferUtility = [AWSS3TransferUtility defaultS3TransferUtility];
// 4. Rewire Transfer Utility blocks
[transferUtility
enumerateToAssignBlocksForUploadTask:^(AWSS3TransferUtilityUploadTask *uploadTask, __autoreleasing AWSS3TransferUtilityUploadProgressBlock *uploadProgressBlockReference, __autoreleasing AWSS3TransferUtilityUploadCompletionHandlerBlock *completionHandlerReference) {
NSLog(#"Upload task identifier = %lu", (unsigned long)uploadTask.taskIdentifier);
// Use `uploadTask.taskIdentifier` to determine what blocks to assign.
//*uploadProgressBlockReference = // Reassign your progress feedback block.
*completionHandlerReference = completionHandler;// Reassign your completion handler.
}
downloadTask:^(AWSS3TransferUtilityDownloadTask *downloadTask, __autoreleasing AWSS3TransferUtilityDownloadProgressBlock *downloadProgressBlockReference, __autoreleasing AWSS3TransferUtilityDownloadCompletionHandlerBlock *completionHandlerReference) {
}];
// 5. Upload data using Transfer Utility
[[transferUtility uploadData:myNSDataObject
bucket:#"bucketName"
key:#"keyName"
contentType:#"text/plain"
expression:expression
completionHander:completionHandler] continueWithBlock:^id(AWSTask *task) {
if (task.error) {
NSLog(#"Error: %#", task.error);
}
if (task.exception) {
NSLog(#"Exception: %#", task.exception);
}
if (task.result) {
AWSS3TransferUtilityUploadTask *uploadTask = task.result;
// 6. Should i be saving uploadTasks here?
}
return nil;
}];

Send attachment to QuickBlox IOS sdk

I have downloaded the quickblox sample chat application and sending text messages are working fine. But how to send attachment like picture, video or else?
According to Quickblox's documentation.
There is class named QBChatAttachment having properties as type, url and id but how to attach files like picture, video or else?
Please Proper read SimpleSample-chat users-ios in this link they have mention all detail regarding how to send attachment and how to receive and download attachment etc .
For sending and receiving attachment in quickbox follow this link
Send and Receive Attachment
Detail Explanation:
Send and receive a message with attachment Send attachment
It's possible to add attachments to message: for example, image, audio
file or video file. We don't have any restrictions here - you can
attach any type of file.
To send a message with attachments you should use the same way as you
send regular message with text, but add to it an attachment object.
Attachment can be:
1) A file content Module Example
2) A file in Custom Objects module Example
To send a message with attachment
you should upload a file to Content module, Custom Objects module
using sample above or use an url to any file in Internet. Then you
should incorporate an ID to file to message.
For example, we use Content module to store attachments. Next snippets
show
how to upload a file to Content module and send it as an attach:
// Upload a file to the Content module
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:#"arrow.png"]);
[QBRequest TUploadFile:imageData fileName:#"arrow.png" contentType:#"image/png" isPublic:NO successBlock:^(QBResponse
*response, QBCBlob *uploadedBlob) {
NSUInteger uploadedFileID = uploadedBlob.ID;
// Create chat message with attach
//
QBChatMessage *message = [QBChatMessage message];
...
QBChatAttachment *attachment = QBChatAttachment.new;
attachment.type = #"image";
attachment.ID = [NSString stringWithFormat:#"%d", uploadedFileID]; //use 'ID' property to store an ID of a file in Content or CustomObjects modules
[message setAttachments:#[attachment]];
} statusBlock:^(QBRequest *request, QBRequestStatus *status) {
// handle progress
} errorBlock:^(QBResponse *response) {
NSLog(#"error: %#", response.error);
}];
Receive attachment
For example we use Content module to store attachments. Next snippets
allow to receive a message with an attachment and download it:
#pragma mark QBChatDelegate
- (void)chatDidReceiveMessage:(QBChatMessage *)message{
for(QBChatAttachment *attachment in message.attachments){
// download file by ID
[QBRequest TDownloadFileWithBlobID:[attachment.ID integerValue] successBlock:^(QBResponse *response, NSData *fileData) {
UIImage *image = [UIImage imageWithData:fileData];
} statusBlock:^(QBRequest *request, QBRequestStatus *status) {
// handle progress
} errorBlock:^(QBResponse *response) {
NSLog(#"error: %#", response.error);
}];
}
}
to obtain a link to attachment and use to show an image:
- (void)chatDidReceiveMessage:(QBChatMessage *)message{
for(QBChatAttachment *attachment in message.attachments){
// or if you have only file ID
NSString *privateUrl = [QBCBlob privateUrlForID:[attachment.ID integerValue]];
}
}
I hope it will be helpful for you.

Google Drive iOS: Upload HTML file to overwrite an existing Docs file

I am trying to write an application that will pull down the contents of a Google Docs file as HTML to allow me to edit it inside the app. After editing the html file I then want to upload the changes back to Google Drive and update the contents of the original Google Docs file. I have been able to pull down the Google Docs file but am not able to upload my changes back to the server.
Can you please help to understand why this error is happening ? And possibly advise me on a fix for the issue ?
I am getting the following NSError:
Error Domain=com.google.GTLJSONRPCErrorDomain Code=500 "The operation couldn’t be completed. (Internal Error)" UserInfo=0x157a8610 {error=Internal Error, GTLStructuredError=GTLErrorObject 0x16846f60: {message:"Internal Error" code:500 data:[1]}, NSLocalizedFailureReason=(Internal Error)}
2014-06-17 12:11:35.188 DrEdit[548:60b] Error UserInfo: {
GTLStructuredError = "GTLErrorObject 0x16846f60: {message:\"Internal Error\" code:500 data:[1]}";
NSLocalizedFailureReason = "(Internal Error)";
error = "Internal Error";
}
Please code being executed when uploading below:
- (void)saveFile {
GTLUploadParameters *uploadParameters = nil;
// Only update the file content if different.
if (![self.originalContent isEqualToString:self.textView.text]) {
// NSData *fileContent =
// [self.textView.text dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString *s = self.textView.attributedText;
NSDictionary *documentAttributes = [NSDictionary dictionaryWithObjectsAndKeys:NSHTMLTextDocumentType, NSDocumentTypeDocumentAttribute, nil];
NSData *htmlData = [s dataFromRange:NSMakeRange(0, s.length) documentAttributes:documentAttributes error:NULL];
// NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
// NSData *fileContent = [self.textView.attributedText convertToData];
uploadParameters = [GTLUploadParameters uploadParametersWithData:htmlData MIMEType:#"text/html"];
// [GTLUploadParameters uploadParametersWithData:fileContent MIMEType:#"text/plain"];
// [GTLUploadParameters uploadParametersWithData:fileContent MIMEType:#"application/vnd.google-apps.document"];
}
self.driveFile.title = self.updatedTitle;
GTLQueryDrive *query = nil;
if (self.driveFile.identifier == nil || self.driveFile.identifier.length == 0) {
// This is a new file, instantiate an insert query.
query = [GTLQueryDrive queryForFilesInsertWithObject:self.driveFile
uploadParameters:uploadParameters];
} else {
// This file already exists, instantiate an update query.
query = [GTLQueryDrive queryForFilesUpdateWithObject:self.driveFile
fileId:self.driveFile.identifier
uploadParameters:uploadParameters];
}
UIAlertView *alert = [DrEditUtilities showLoadingMessageWithTitle:#"Saving file"
delegate:self];
[self.driveService executeQuery:query completionHandler:^(GTLServiceTicket *ticket,
GTLDriveFile *updatedFile,
NSError *error) {
[alert dismissWithClickedButtonIndex:0 animated:YES];
if (error == nil) {
self.driveFile = updatedFile;
self.originalContent = [self.textView.text copy];
self.updatedTitle = [updatedFile.title copy];
[self toggleSaveButton];
[self.delegate didUpdateFileWithIndex:self.fileIndex
driveFile:self.driveFile];
[self doneEditing:nil];
} else {
NSLog(#"An error occurred: %#", error);
NSLog(#"Error UserInfo: %#", error.userInfo);
[DrEditUtilities showErrorMessageWithTitle:#"Unable to save file"
message:[error description]
delegate:self];
}
}];
}
Thanks,
Michael
Its not possible to write html to a gdoc programmatically.
Currently its only possible to manually paste html but not with an api unfortunately (and strangely)
I was able to solve this problem by changing the property convert to YES on the GTLQueryDrive class. The documentation states that it will attempt to convert the file being uploaded into a native Google Docs format.
Hope this helps. Please see the method I am describing from the SDK below:
// Method: drive.files.update
// Updates file metadata and/or content
// Required:
// fileId: The ID of the file to update.
// Optional:
**// convert: Whether to convert this file to the corresponding Google Docs
// format. (Default false)**
// newRevision: Whether a blob upload should create a new revision. If false,
// the blob data in the current head revision will be replaced. (Default
// true)
// ocr: Whether to attempt OCR on .jpg, .png, or .gif uploads. (Default false)
// ocrLanguage: If ocr is true, hints at the language to use. Valid values are
// ISO 639-1 codes.
// pinned: Whether to pin the new revision. (Default false)
// setModifiedDate: Whether to set the modified date with the supplied
// modified date. (Default false)
// sourceLanguage: The language of the original file to be translated.
// targetLanguage: Target language to translate the file to. If no
// sourceLanguage is provided, the API will attempt to detect the language.
// timedTextLanguage: The language of the timed text.
// timedTextTrackName: The timed text track name.
// updateViewedDate: Whether to update the view date after successfully
// updating the file. (Default true)
// Upload Parameters:
// Maximum size: 10GB
// Accepted MIME type(s): */*
// Authorization scope(s):
// kGTLAuthScopeDrive
// kGTLAuthScopeDriveFile
// Fetches a GTLDriveFile.
+ (id)queryForFilesUpdateWithObject:(GTLDriveFile *)object
fileId:(NSString *)fileId
uploadParameters:(GTLUploadParameters *)uploadParametersOrNil;
Thanks,
Michael

Resources