How to get the FBProfile picture into UIImageView - ios

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

Related

How to download an image using QuickBox API?

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

Parse get facebook profile picture when user is logged in

I'm new to parse and i've just implemented a facebook log in using parse. In my app i need the facebook profile picture of the person who is logged in. i've created that method, but dont know if there is a simpler way.
This method takes time to load which is not very nice. Can i load the profile picture somehow when the person is logged in and then use it in another viewcontroller?
here is my code at the moment:
// After logging in with Facebook
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *facebookId = [result objectForKey:#"id"];
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large", facebookId ]]]];
[self.tableView reloadData];
}
}];
This isn't actually anything to do with Parse. It's just Facebook SDK.
What you need to do is store the image somewhere so that you can get it if it already exists.
The easiest (but arguably not best) way is to use a singleton.
Create a singleton object with a property...
#interface MySingleton : NSObject
#property (nonatomic, strong) UIImage *userImage;
+ (instancetype)sharedInstance;
#end
Then you can just check if it exists before downloading...
UIImage *theImage = [[MySingleton sharedInstance] userImage];
if (!theImage) {
// download the image from Facebook and then save it into the singleton
}
Once it is downloaded you can then just get it from the singleton without having to download it every time.

iOS - Retrieve Picture from Parse currentUser

I'm using Parse.com as a backend for my iOS app.
I have a class called "User".
In this class I have a flied called "picture" with the users profile picture.
At the moment im kinda stuck on how i can fetch this picture for my currentUser and show it within an UIView (not UIImage) within my storyboard viewcontroller.
Maybe you guys have some sample code for that?
Thanks in Advance!
Amit, sorry your Code didnt work for me, my app crashed.
Here is my solution:
PFUser *cUser = [PFUser currentUser];
PFFile *pictureFile = [cUser objectForKey:#"picture"];
[pictureFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error){
[_currentUserImage setImage:[UIImage imageWithData:data]];
}
else {
NSLog(#"no data!");
[_currentUserImage setImage:[UIImage imageNamed:#"profile"]]; //Set Custom Image if there is no user picture.
}
}];
}

Get Spotify Track artwork on UITableView

I am trying to get artworks or album covers using spotify API. I am using:
NSString *url = #"http://ws.spotify.com/search/1/track.json";
NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
([Utils isEmptyString:_searchBar.text] ? #"music" : _searchBar.text), #"q", nil];
[self sendRequestWith:url params:params method:RequestMethodGET success:^(AFHTTPRequestOperation *operation, id response, NSDictionary *userData) {
NSDictionary *result = (NSDictionary *)response;
if(result){
[_trackList removeAllObjects];
NSArray *tracks = [Utils getDictionaryValue:result by:#[#"tracks"]];
for (NSDictionary *trackData in tracks) {
WPTrack *track = [[WPTrack alloc] initWithSpotifyJSON:trackData];
[_trackList addObject:track];
}
[listViewController updateWithObjects:_trackList];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error, NSDictionary *userData) {
} userData:nil];
The current method I am getting doesn't seem to return the thumbnail of the track. But it returns "href" of the track which I can use to search for the track's image by https://embed.spotify.com/oembed/?url=spotify:track:6bc5scNUVa3h76T9nvpGIH. However, this might be another request which could slow my loading on the UITableView. Is there a better way to do this process together?
It common practice to not include rich media content in a api response as the client will have to wait until everything has been sent which can take a long time. To speed up the process you should parser the information gathered and display that to the user while you have another asynchronously operation using a Block to retrieve the image and display it.
Using Async call with cell example

How to show progressive hud/ activity indicator with box sdk

I have successfully integrate BOX SDK in my ios app, but facing an issue while uploading a file to box, my issue is i did not able to hide progress indicator/hud after success full upload in success block. I am not much aware of block code. I have used this code for uploading file
-(void)upload{
BoxFilesRequestBuilder *builder = [[BoxFilesRequestBuilder alloc] init];
builder.name = #"Logo_Box_Blue_Whitebg_480x480.jpg";
builder.parentID = folderID;
NSString *path = [[NSBundle mainBundle] pathForResource:#"Logo_Box_Blue_Whitebg_480x480.jpg" ofType:nil];
NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:path];
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
long long contentLength = [[fileAttributes objectForKey:NSFileSize] longLongValue];
[[BoxSDK sharedSDK].filesManager uploadFileWithInputStream:inputStream contentLength:contentLength MIMEType:nil requestBuilder:builder success:fileBlock failure:failureBlock progress:nil];
}
On successful upload this method is called and i want to hide my progress hud in this block, how to do this.
BoxFileBlock fileBlock = ^(BoxFile *file)
{
// manipulate resulting BoxFile
};
BoxAPIJSONFailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
{
// handle failed upload
};
Have you tried hiding HUD both from success and failure blocks?
Either one of them will get called eventually.
In your code above, I can't see any HUD object or property
It is also not clear if upload method belongs to the ViewController class with HUD pointer.
Option A
Assuming that upload method belongs to the view controller with HUD.
class declarations in MyAwesomeBOXUploadViewController.m (replace with your view controller class name :) )
#interface MyAwesomeBOXUploadViewController ()
#property (nonatomic, readwrite, strong) MyHUD *uploadHUD;
#end
from success failure blocks MyAwesomeBOXUploadViewController implementation.
// using weak pointer to self to avoid retain loop
__weak MyViewControllerClass *weakSelf = self;
BoxFileBlock fileBlock = ^(BoxFile *file)
{
[weakSelf.uploadHUD stop];
// manipulate resulting BoxFile
};
BoxAPIJSONFailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
{
[weakSelf.uploadHUD stop];
// handle failed upload
};
Option B
If upload method is not part of view controller and you don't have HUD pointer, then you need to propagate success and fail callbacks up to the view Controller. To propagate success/failure you have a bunch of options. One might consider using block callbacks or nsnotifications.
BTW, Blocks can be extremely useful and Apple provides great documentation on block programming:
https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html

Resources