I'm trying to download an image file using Quickblox API. I can upload a file but when I try to download, NSData image doesn't show an image.
// Upload a user avatar, previously log in Quickblox API
NSData *avatar = UIImagePNGRepresentation([UIImage imageNamed:#"userWhite"]);
[QBRequest TUploadFile:avatar fileName:#"avatar.png" contentType:#"image/png" isPublic:YES successBlock:^(QBResponse *response, QBCBlob *blob) {
// Success
} statusBlock:^(QBRequest *request, QBRequestStatus *status) {
} errorBlock:^(QBResponse *response) {
}];
Image Upload: Image
Download avatar:
NSString* userProfilePictureID = [NSString stringWithFormat:#"%ld",(long)[[LocalStorageService shared] currentUser].blobID]; // user - an instance of QBUUser class
// download user profile picture
[QBRequest downloadFileWithUID:#"318547" successBlock:^(QBResponse *response, NSData *fileData) { UIImage* image = [UIImage imageWithData:fileData];
} statusBlock:^(QBRequest *request, QBRequestStatus *status) {
} errorBlock:^(QBResponse *response) {
}];
UIImage doesn't show any image. What can I do? NSData isn't corrupted.
Your download code looks right. You basically should call QBRequest method and pass blob.UID to it.
But in my case blob.UID is something like this 9357c3d66b944880a82cdbeb836f143c00. However there are steps I took to accomplish your task:
1) Sign up or login user
Either by calling +[QBRequest signUp:successBlock:errorBlock:] or +[QBRequest logInWithUserLogin:password:successBlock:errorBlock].
2) Enumerate through all available blobs for current user
[QBRequest blobsWithSuccessBlock:^(QBResponse* response,
QBGeneralResponsePage* page,
NSArray* blobs) {
[self findAndShowAvatarFromBlobs:blobs];
} errorBlock:^(QBResponse* response) { <...> }];
3) Find desired blob and download it
- (void)findAndShowAvatarFromBlobs:(NSArray*)blobs {
for (QBCBlob* blob in blobs) {
if ([blob.name hasPrefix:#"avatar"]) {
[QBRequest downloadFileWithUID:blob.UID
successBlock:^(QBResponse* response, NSData* fileData) {
UIImage* image = [UIImage imageWithData:fileData];
self.imageView.image = image;
}
statusBlock:^(QBRequest* request, QBRequestStatus* status) { <...> }
errorBlock:^(QBResponse* response) { <...> }];
}
}
}
Probably you have a problem with getting valid blob UID (I suspect that you are using blob ID which is not the same as UID). Is it possible for you to use the same kind of logic?
Full project you can find here: https://dl.dropboxusercontent.com/u/930742/so/QuickBloxSample.zip
It creates necessary user, uploads and then downloads image with showing it in UIImageView demonstrating all described steps. (Don't forget to set your service and application keys in AppDelegate)
P.S. In admin panel you can find blob UID by clicking on its ID in Content table
Related
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.
I'm wondering what is the best way to set images in my UITableView from the server. I'm storing images on the amazon s3 and to get images I have implemented logic in the backend that require two statements:
first one I'm using to get url of image and in the second one I just simply display images to the UITableViewCell. For web requests I'm using AFNetworking library and addition to UIImageView (<UIImageView+AFNetworking.h>). I don't have a problem with requests, however I'm not quite sure where should I put my code responsible for getting all urls of the images. It seems to me that cellForARowAtIndexPath method is good only for displaying images from the final url address:
Here is my code.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"final url here"]];
[cell.imageView setImageWithURLRequest:request placeholderImage:[UIImage imageNamed:#"GeofencingAlert.png"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage
*image)
{
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(#"Error: %#",error.description);
}];
Should I first download all of the url stored on the amazon s3 and put them into the NSMutuableArray ? If yes what is the best way to execute multiple requests? What if the user add new record to the table ? Do I have to execute multiple requests again to keep my UITableVIewCell images updated? Thanks in advance.
You should use -(void)viewDidLoad method. Something like this
- (void)viewDidLoad
{
urlPaths = nil;
[httpClient loadUrlsWithSuccess:^(NSArray *results){
urlPaths = results; // urlPaths - class member
[tableView reloadData];
}];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath)indexPath
{
//...
if(urlPaths)
{
NSString *urlPath = urlPaths[indexPath.row];
// load async
}
else
// urls are not loaded yet
imageView.image = placeholderImage;
}
I have an iOS app that integrated with FBLoging. And I know it can assign the profile picture into a UIView like this.
// This method will be called when the user information has been fetched
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
self.profilePictureView.profileID = user.id;
}
But what I wanna do is to get that profile picture into my already available UIImageView. In order to do this I have a Singleton class. I want to get that image as a UIImage and assign to the variable inside that Singleton class. When another Viewcontroller load I want to assign that singleton class's UIImage into my Viewcontroller's UIImageView
How can I do this. please help me.
Thank you
If you have Facebook user.id with you, you can create the imageURL like this
NSString * url = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large",user.objectID];
Then save this url to your singleton class. And you can download like this if you need.(You can download each time you required or download once and save in to a file, if required ,fetch from file).
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
UIImage *userImage = [UIImage imageWithData:data];
You can get the image from the profilePictureImageView using this answer .
Once you have the image, then you can save it in your Singleton class as is or you can assign it to your imageView.
The method in the link only works once the image has been downloaded into the profilePictureImageView. So you need to take care of that, maybe by waiting. Or keep checking it for non nil value after some time in succession.
you can try following method
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *FBuser, NSError *error) {
if (error) {
// Handle error
}
else {
NSString *userName = [FBuser name];
NSString *userImageURL = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large", [FBuser id]];
}
}];
you have to store this url into your singleton class
I am working on Game Center for iOS devices using the sandbox environment. I am trying to load the achievement images I set up in iTunes Connect.
I am using loadAchievementDescriptionWithConpletionHandler successfully.
The problem happens when I try to load the image using loadImageWithCompletionHandler.
[self.description loadImageWithCompletionHandler:^(UIImage *image, NSError *error) {
if (!error) {
self.achievementImage = image;
}
}];
The problem is both the UIImage and the error are nil.
It is due to the sandbox environment ? Am I missing something ?
Thanks
I can load the image successfully. It looks like my image format was wrong.
I have deleted the achievement and created a new one using a 512x512 72 dpi image.
Using loadAchievementDescriptionsWithCompletionHandler. I load all the achievementDescriptions from Game Center. Then, I use loadImageWithCompletionHandler to extract the image.
[GKAchievementDescription loadAchievementDescriptionsWithCompletionHandler:^(NSArray *descriptions, NSError *error) {
if (!error) {
for (GKAchievementDescription *achievementDescription in descriptions) {
[self.achievementDescriptionDictionary setObject:achievementDescription
forKey:achievementDescription.identifier];
[achievementDescription loadImageWithCompletionHandler:^(UIImage *image, NSError *error) {
if (!error) {
if (image) {
UIImage *achievementimage = image;
}
}
}];
}
}
}];
I am working on an app which is image downloading. Images are of different sizes. I want to download image async and update table view when image downloading. Also need to clear cache on a time interval.
Please suggest me how to implement. I have seen SDwebimagecache but it is crashing on image downloading.
I hope it's can help you. I use SDWebImage with my all (ARC)projects.
using :
add your viewcontroller : #import "UIImageView+WebCache.h"
[yourImageView setImageWithURL:[NSURL URLWithString:#"ImageUrl"]];
you need to add MapKit and ImageIO to the project. if you didn't add
To do that:
Click on the project at the top of the project navigator in Xcode
Select the 'Build Phases' tab.
Open up the 'Link Binary with Libraries' box.
Click the '+'.
Add MapKit and ImageIO frameworks.
I have used the core data and AFNetworking to achieve the same thing, find below my code
UserBasicInfo* userBasicInfo = [[UserBasicInfo findByAttribute:#"userId" withValue:#(chatUser)] objectAtIndex:0];;
if (userBasicInfo.userImage == nil) {
__weak LGMessageBoxCell *weakCell = cell;
[cell.userImage setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:userBasicInfo.imageUrl]]
placeholderImage:[UIImage imageNamed:#"facebook-no-user.png"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
weakCell.userImage.image = image;
[weakCell setNeedsLayout];
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
UserBasicInfo* userBasicInfo = [[UserBasicInfo findByAttribute:#"userId" withValue:#(chatUser) inContext:localContext] objectAtIndex:0];
userBasicInfo.userImage = UIImagePNGRepresentation(image);
} completion:^(BOOL success, NSError *error) {
NSLog(#"%#",[error localizedDescription]);
}];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
}];
} else {
cell.userImage.image = [UIImage imageWithData:userBasicInfo.userImage];
}