Facebook iOS-sdk and posting a local (UI)Image - facebook-graph-api

I have successfully used photos.upload api to upload local images to the users album.
How to upload local images with formatted links? The photos.upload does support adding the caption text, but I can't embed html-links to the caption. Is there a way to do this using perhaps the Graph-api?

I'm not sure about the caption itself, but here is a way to post the image along with a message to the user's wall. The message text can have imbedded links in it with no problem.
Facebook* fb = [(AppDelegate *) [[UIApplication sharedApplication] delegate] facebook];
NSData* imageData = UIImageJPEGRepresentation([UIImage imageNamed: #"A.jpg"], 90);
NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys: [fb accessToken],
#"access_token",
#"some message here...with a link http://www.google.com",
#"message",
imageData,
#"source",
nil];
[fb requestWithGraphPath: #"me/photos"
andParams: params
andHttpMethod: #"POST"
andDelegate: self];

Related

Sitecore How to get the value inside the field 'Media' of a Media Item

Update 2:
I am still fighting to get the Icon save on the server.
Here what I am doing:
Item item = Sitecore.Context.Database.GetItem(imageId);
var imageIconUrl = Sitecore.Resources.Images.GetThemedImageSource(item.Appearance.Icon, ImageDimension.id32x32);
if (!string.IsNullOrEmpty(imageIconUrl))
{
// download the icon from the url
var iconFullPath = "e:\\pngIcons\\excelIcon.png";
var webClient = new System.Net.WebClient();
var downloadPath = "http://serverName/" + imageIconUrl;
webClient.DownloadFile(downloadPath, iconFullPath);
}
The variable downloadPath contains following string:
http://serverName/sitecore/shell/themes/standard/~/media/E503BA48C89B422D8400393F1C7086A7.ashx?h=32&thn=1&w=32&db=master
At the end what I can see is a png file but there is nothing in it. I also copy the string I get in variable downloadPath and pasted it in browser and I can see the Icon as follow:
Please let me know what I am doing wrong. Or How I can save the Icon. Thanks!!
Original Question:
The sitecore media item has a field "Media". I am talking about this:
I want to access this field. And the reason is:
If I access it with e.g. item.GetMediaStream() then I will get the complete file. I just want to save this little icon some how on the server. Is it possible ?
To get the icon/thumbnail you can use
var icon = Sitecore.Resources.Media.MediaManager.GetThumbnailUrl(mediaItem);
To get the url of the thumbnail.
If you want the stream of the thumbnail you need to use the MediaData object. Like this:
var mediaItem = new MediaItem(item)
var mediaData = new MediaData(mediaItem);
var iconStream = mediaData.GetThumbnailStream();
if (iconStream.Length < 0)
{
// The stream is empty, its probably a file that Sitecore can't
// generate a thumbnail for. Just use the Icon
var icon = item.Appearance.Icon;
}
This will get the icon or thumbnail of the actual media blob that is attached to the media item. If you just want the icon of the Sitecore item, then use Martins method.
If the stream is empty, then Sitecore can't generate a thumbnail for it, so you can just use the icon file for the media item template. item.Appearance.Icon
Appearance section (of Standard Template) has a field called Icon - this is where you can modify icon for the item. There is also a field called Thumbnail - your excel icon is sitting there
You can access the field programmatically, just mind that it starts with two underscores: __Icon:
var iconField = item.Fields["__Icon"];
var thumbnailField = item.Fields["__Thumbnail"];
Update: As you asked, below is the code that saves either of fields into the file on a drive. I have tested the code and confirm successfully stores icon from thumbnail field into the file:
string mediaItemPath = "/sitecore/media library/Files/ExcelFile";
string mediaFiedlName = "Thumbnail"; // also can be "__Icon"
var item = Sitecore.Context.Database.GetItem(mediaItemPath);
var iconField = item.Fields[mediaFiedlName];
if (iconField.HasBlobStream)
{
var thumb = (ImageField)iconField;
var bl = ((MediaItem)thumb.MediaItem).InnerItem.Fields["blob"];
Stream stream = bl.GetBlobStream();
byte[] buffer = new byte[8192];
using (FileStream fs = File.Create("D:\\you_file_name.ico")) // change your path
{
int length;
do
{
length = stream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, length);
}
while (length > 0);
fs.Flush();
fs.Close();
}
}
Update 2: If that does not help then I would advise to look around the way how that icon gets generated on Media field in Sitecore. In the worst case you may do the following - right click that icon and see its url. You will have something similar to what I assign to variable below:
string url = "http://test81/sitecore/shell/Applications/-/media/B4F61650CBE84EE396649602C0C48E1B.ashx?bc=White&db=master&h=128&la=en&mw=640&thn=1&vs=1&ts=b8046903-ae57-4f9d-9dd5-b626ee5eee90";
Of course your URL should have your hostname and media prefix and the rest of parameters. Then use Webclient with that modified URL:
WebClient webClient = new WebClient();
webClient.DownloadFile(url, "e:\\you_file_name.ico");
Not ideal, but may work. Note, that the code above should work in a context of already logged user, so you need to authorise you Webclient prior that (many articles on S.O. how to do that).
Please reply if that approach has worked for you (I've spent decent time writing and testing that code in debugger, so would want to know whether that helped)

Facebook profile picture not showing in UIImageView?

I am building a facebook app. Where I have to show my friends profile picture. But the image is not showing all the time when I run my project. I have used the code like tha
NSString *url = [NSString stringWithFormat:#"http://graph.facebook.com/%#/picture? type=large",friendId];
NSData *imageUrl = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:imageUrl]];
imgView.frame = CGRectMake(100.0f,100.0f,200,200);
[self.view addSubview:imgView];
But when I am printing the url in log then it shows an url and if I go with this url in browser then It shows picture in the browser.
For printing the URL I used the code below:
NSLog(#"%#",url);

saving integer when app is quit - apple iOS

right ive got this code below which will save a integer when the save button is clicked and the app is shut however i need it to do this automatically... how do I go about doing this with ios? quite new to the whole apple coding thing so any help is welcome
-(IBAction)SaveNumber:(id)sender{
[[NSUserDefaults standardUserDefaults] setInteger:Number forKey:#"savenumber"];
}
- (void)viewDidLoad {
Number = [[NSUserDefaults standardUserDefaults] integerForKey:#"savenumber"];
ShowSavedNumber.Text = [NSString stringWithFormat:#"%i",Number];
[super viewDidLoad];
}
The problem is, where you try to save this value? you don't have a file to storage this value in Documents directory inside the App.
You can save any value in your app, but you have to use a file for storage and read, or saving and load via URL on your server. Like file.plist, SqlLight, json with MySql.
So the first simple saving is using a file .plist inside your app, under the AppDelegate.m you have to check your directory if the file exist and copy inside a Documents directory (the only writable folder), but after that you have to learn how to load and save on the same file using Dictionary , MutableDictionary and some other class. I can help you to understant the first steps like a check and create a .plist, read, and first base to save, but for other thing is to much code and yopu have to watch other tutorials.
So create a .plist file and change the structure like this:
Change key has you want, but remember the Dictionary contain more string value, if you want add more Item you have to add other row inside the same Root Array.
Root = Array
Item0 > some string with value
Item1 > some string with value
Now you have to copy this file inside a writable Documents folder when the application lauching, so inside your AppDelegate.m create a function:
- (void)createPlistFile{
NSError *error;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"yourFile.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"yourFile" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error];
}
}
Under the - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { add a call: [self createPlistFile];
Ok now you have Check first if the file exist in documents folder, and if is false, the app create a new file.
Now here the standard code to read a new file inside your app:
in your ViewControlle.h write:
#interface ViewController : UIViewController {
NSMutableArray *loadData;
}
#property (nonatomic, strong) NSMutableArray *loadData;
Come back to your ViewController.m and write:
#synthesize loadData;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"yourFile.plist"];
NSMutableArray *dataDict = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
self.loadData = dataDict;
Ok now you have create a new PLIST file inside a Documents Directory an correctly load, but now you have to save, this is a basic method to save, but theres really many mode for that and I can't write all here ;)
- (IBAction)save:(id)sender {
NSMutableDictionary *nr2 = [[NSMutableDictionary alloc] init];
[nr2 setValue:emittente.text forKey:#"plistKey"];
[nr2 setValue:link.text forKey:#"plistKey"];
[nr2 setValue:images.text forKey:#"plistKey"];
[nr2 setValue:web.text forKey:#"plistKey"];
[YouMutableDict addObject:nr2];
[YouMutableDict writeToFile:listFav atomically:YES];
}
Ok that's all I hope this help you to start understand how to save Data on app if yes please vote ;)
Changes made to NSUserDefaults are not automatically saved. You must call -synchronize on the NSUserDefaults object in order to save. Generally you want to do this once after you have made all of the updates you plan on performing (if in fact you need to do multiple updates).
Here is Apple's reference: http://developer.apple.com/library/ios/ipad/#documentation/cocoa/reference/foundation/Classes/NSUserDefaults_Class/Reference/Reference.html

How to post to a friend's wall in facebook iOS SDK 3.1?

I have the SDK 3.1 working for iOS 6 for posting status updates and I have the facebook user id of the person who I want to post on their wall.
I just want it to say "hi." to just one person's wall.
I can target their feed with "/[id]/feed" but then I have to supply a graph object? if I use startForPostWithGraphPath() anyways.
I figured it out!
First of course implement FBFriendPickerDelegate per here, unless you already have their friend ID somehow. http://developers.facebook.com/docs/howtos/filter-devices-friend-selector-using-ios-sdk/
Then the important part, how to post to friend's wall:
- (void)facebookViewControllerDoneWasPressed:(id)sender
{
NSString* fid;
NSString* fbUserName;
// get facebook friend's ID from selection. just gets 1 right now.
for (id<FBGraphUser> user in friendPickerController.selection)
{
NSLog(#"\nuser=%#\n", user);
fid = user.id;
fbUserName = user.name;
}
//Make the post.
NSMutableDictionary* params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Join me!", #"message", #"http://itunes.apple.com/my-super-app", #"link", #"My Super App", #"name", nil];
NSLog(#"\nparams=%#\n", params);
//Post to friend's wall.
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/feed", fid] parameters:params HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
//Tell the user that it worked.
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Shared"
message:[NSString stringWithFormat:#"Invited %#! error=%#", fbUserName, error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
];
//Close the friend picker.
[self dismissModalViewControllerAnimated:YES];
}

How to print xml image in IOS?

I've created a simple XML-Parser to parse my rss Feeds to my app.
The id, currentstatus, picture of the simple to parse from the xml file.
But I can't get the image from the XML file. . i retrieve the all the images from xml file. but the noimage.jpg not displaying. could you please any help me.
XML code
<Agent>
<id>3422</id>
<currentstatus>Logged Off</currentstatus>
<picture>1</picture>
</Agent>
<Agent>
<id>3432</id>
<currentstatus>Logged Off</currentstatus>
<picture>0</picture>
</Agent>
i tried the following code:
UIImage * cellimages = [[UIImage alloc]init];
NSString *string1 = #"http://telecomstats.co.uk/images/LLReaderProfile/";
NSString *cellvalue =[[[[self rssParser]rssItems]objectAtIndex:indexPath.row]picture];
NSString* disable = [[NSString alloc] initWithString:#"0"];
if (cellvalue == disable)
{
cellimages = [UIImage imageWithContentsOfFile:#"http://telecomstats.co.uk/images/LLReaderProfile/noimage.jpg"];
}
else {
cellimages = [string1 stringByAppendingString:[[[[self rssParser]rssItems]objectAtIndex:indexPath.row]id]];
cellimages = [cellimages stringByAppendingString: #".jpg"];
}
cellimages = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:cellimages]]];
cell.imageView.image = cellimages;
Does someone can help me?
Thanks for any help and insight.
You're using cellimages which is an UIImage object to store strings in your else-branch. Also when cellvalue == disable is true, you execute this:
cellimages = [UIImage imageWithContentsOfFile:#"http://telecomstats.co.uk/images/LLReaderProfile/noimage.jpg"];
cellimages = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:cellimages]]];
There you put an UIImage in [NSURL URLWithString:] which probably will not work; actually this code should produce quite some warnings. Try to properly separate between the URL string and the image object to display. Put all URL stuff in an NSString and get the UIImage afterwards when you have determined the correct URL.
Note that your code has some other problems, especially that you are using dataWithContentsOfURL and imageWirhContentsOfFile both of which will block until the image is retriebes. This will result in application hangs when using a bad internet connection and if the network is too slow, will crash your app. Have a look into asynchronous downloads and using frameworks like AFNetworking.