How to share text over to Tumblr using Xcode - iphone

I am working on an iOS application which has sharing functionality like Facebook, Twitter and Tumblr Sharing. I have done all sharing besides the Tumblr.
I've worked a lot on this. I have done a lot of googling, but found nothing on Tumblr Sharing. Here is my code currently using for sharing text over Tumblr :
- (void)shareOvertumblr:(id)sender
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:
[NSURL URLWithString:#"http://www.tumblr.com/api/write"]];
[request setHTTPMethod:#"POST"];
//tell the server to expect 8-bit encoded content as we're sending UTF-8 data,
//and UTF-8 is an 8-bit encoding
[request addValue:#"8bit" forHTTPHeaderField:#"Content-Transfer-Encoding"];
//set the content-type header to multipart MIME
[request addValue: [NSString stringWithFormat:#"multipart/form-data; boundary=%#",[NSString MIMEBoundary]] forHTTPHeaderField: #"Content-Type"];
//create a dictionary for all the fields you want to send in the POST request
NSDictionary* postData = [NSDictionary dictionaryWithObjectsAndKeys:
#"myEmailAddress", #"email",
#"password", #"password",
#"regular", #"type",
#"myTitle", #"title",
#"Hiiii How ruuu", #"body",
nil];
//here inPlace of these EmailAddress and Password using my correct emailAdress and Password
//set the body of the POST request to the multipart MIME encoded dictionary
[request setHTTPBody: [[NSString multipartMIMEStringWithDictionary: postData] dataUsingEncoding: NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
/*Here is The Category */
#interface NSString (MIMEAdditions)
+ (NSString*)MIMEBoundary;
+ (NSString*)multipartMIMEStringWithDictionary:(NSDictionary*)dict;
#end
#implementation NSString (MIMEAdditions)
//this returns a unique boundary which is used in constructing the multipart MIME body of the POST request
+ (NSString*)MIMEBoundary
{
static NSString* MIMEBoundary = nil;
if(!MIMEBoundary)
MIMEBoundary = [[NSString alloc] initWithFormat:#"----_=_YourAppNameNoSpaces_%#_=_----",[[NSProcessInfo processInfo] globallyUniqueString]];
return MIMEBoundary;
}
//this create a correctly structured multipart MIME body for the POST request from a dictionary
+ (NSString*)multipartMIMEStringWithDictionary:(NSDictionary*)dict
{
NSMutableString* result = [NSMutableString string];
for (NSString* key in dict)
{
[result appendFormat:#"--%#\nContent-Disposition: form-data; name=\"%#\"\n\n%#\n", [NSString MIMEBoundary],key,[dict objectForKey:key]];
}
[result appendFormat:#"\n--%#--\n",[NSString MIMEBoundary]];
return result;
}
#end
/*Connection Delegate Methods*/
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[self.view setUserInteractionEnabled:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
webData = [[NSMutableData alloc] initWithLength:0];
// webData is The NSMutable data
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString* responseString = [[NSString alloc] initWithData: webData
encoding: NSUTF8StringEncoding];
NSLog(#"Response String %#",responseString);
// here i got Authentication failed as Response .....
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[webData appendData:data];
}
Whenever i run this code getting some Authentication failed error.
I have seen the same issue on various thread. Here is the link I have tried
But unfortunately no luck so far. Please help.

Instead of your own code, you can use ShareKit
It will add full sharing capabilities to your App with just 3 line of code.
ShareKit is an open source framework that can be dropped into any iPhone or iPad app to instantly add full sharing capabilities.
You can use ShareKit to add sharing URLs, images, and text with Tumblr in just a few lines of code.
Sharing Text
+ (SHKItem *)text:(NSString *)text;
NSString *someText = #"This is a blurb of text I highlighted from a document.";
SHKItem *item = [SHKItem text:someText];
You can see more details here

Related

HTTP-connection with credentials to get HTML document

I would like to download an HTML documents(s) to parse the content. The server asks before entering this site to put in my user credentials. In Java I arrived with a basic authentication in an asynchronous task like this (JSoup):
String base64login = new String(Base64.encodeBase64(loginDaten.getBytes()));
Document parsableDoc = Jsoup.connect(myUrl).header("Authorization","Basic"+base64login)
.timeout(3000)
.get();
but in Objective-C it doesn't work so simple as I thought. Here I want to save the website in an NSData-Object or something similar (for example NSString). Got any ideas to solve this as simple as possible? (I'm such a pro in this sector as you can see…)
You can do this using the NSURLConnection class ad NSMutableURLRequest. The idea is that you let the NSMutableURLRequest know what kind of auth method you want to use, and the credentials (login/password).
The following code should do it. (You will need the NSdata category for base64Encoding in this link http://cocoadev.com/wiki/BaseSixtyFour )
self.receivedData = [[NSMutableData alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"login",#"password"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64Encoding]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if ([self.receivedData length] >0)
NSString *result = [[NSString alloc] initWithData:downloadedData encoding:NSUTF8StringEncoding];
NSLog(#"The HTML String Is : %#", result);
{

How to login a server and get page source on objective-c?

I am trying to login a server by sending my username and password by POST method by NSURLConnection on objective-c but I get this from my NSLog
NSLog:
NSLog:
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",string);
What it writes to the console:
404 Not Found
Not Found
Sorry!The page requested was not found.
Why does this happens? Why do I get Not Found page instead of the index page? What do I do wrong? By the way I am trying to connect https not http I don't know does Here is the source code:
#interface ProjectViewController ()
#property NSURLConnection * urlConnection;
#property NSMutableData * responseData;
#end
#implementation ProjectViewController
#synthesize responseData =_responseData;
- (IBAction)LoginButton:(UIButton *)sender {
NSMutableURLRequest *request = nil;
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://loginpage.com"]];
NSString *post = [NSString stringWithFormat:#"sid=%#&PIN=%#", #"username", #"password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval: 15];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
_urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[_urlConnection start];
//[self performSegueWithIdentifier:#"LoginComplete" sender:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",string);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//Oops! handle failure here
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
//NSDictionary *headerFields = [(NSHTTPURLResponse*)response allHeaderFields]; //This would give you all the header fields;
//NSLog(#"%#",headerFields);
}
}
#end
What I just recognized is if I put the part of POST request in to comment it prints the page source to the console but of course I can't send my username and password to the server. I just get the login page's source code but I want to get the source code after I login. Actually I want to redirect to another page by using this session.
This part:
NSString *post = [NSString stringWithFormat:#"sid=%#&PIN=%#", #"username", #"password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval: 15];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
is the certificate used on the website self signed? did you try to make the request in a webview to see if it works there? not in an nsurlrequest?
try this response maybe it will give you some hints.

Objective C - POST data using NSURLConnection

I'm very slowly working my way through learning the URL loading system for iOS development, and I am hoping someone could briefly explain the following piece of code:
NSString *myParameters = [[NSString alloc] initWithFormat:#"one=two&three=four"];
[myRequest setHTTPMethod:#"POST"];
[myRequest setHTTPBody:[myParameters dataUsingEncoding:NSUTF8StringEncoding]];
Eventually I would like to be able to create an application that logs into my ISP's website and retrieves how much data I have left for the rest of the month, and I feel as though I should get my head around setHTTPMethod/setHTTPBody first.
Kind regards
This is a pretty simple HTTP request setup; if you have more specific questions you might do better asking those.
NSString *myParameters = #"paramOne=valueOne&paramTwo=valueTwo";
This sets up a string containing the POST parameters.
[myRequest setHTTPMethod:#"POST"];
The request needs to be a POST request.
[myRequest setHTTPBody:[myParameters dataUsingEncoding:NSUTF8StringEncoding]];
This puts the parameters into the post body (they need to be raw data, so we first encode them as UTF-8).
Step 1 : set URL definitions:
// Create the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.0.232:8080/xxxx/api/Login"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];
[postDict setValue:#"Login" forKey:#"methodName"];
[postDict setValue:#"admin" forKey:#"username"];
[postDict setValue:#"123456" forKey:#"password"];
[postDict setValue:#"mobile" forKey:#"clientType"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSString *urlString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [[NSString alloc] initWithFormat:#"jsonRequest=%#", urlString];
//#"jsonRequest={\"methodName\":\"Login\",\"username\":\"admin\",\"password\":\"12345678n\",\"clientType\":\"web\"}";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (!theConnection) {
// Release the receivedData object.
NSMutableData *responseData = nil;
// Inform the user that the connection failed.
}
Step 2:
// Declare the value for NSURLResponse URL
//pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
NSError *error=nil;
// Convert JSON Object into Dictionary
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:_responseData options:
NSJSONReadingMutableContainers error:&error];
NSLog(#"Response %#",JSON);
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
The first line created an string, it can be replaced with:
NSString *myParameters = #"one=two&three=four";
It's written in initWithFormat so you can extend it to assign parameter value.
Second line indicate this is HTTP post request.
The third line, setHTTPBody method take NSData type, so you need to convert string type to NSData using dataUsingEncoding method.
please use below code.
+(void)callapi:(NSString *)str withBlock:(dictionary)block{
NSData *postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#“%#/url”,WebserviceUrl]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:120.0];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (!data) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithFormat:#"%#",AMLocalizedString(SomethingWentWrong, nil)] forKey:#"error"];
block(dict);
return ;
}
NSError *error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
//////NSLog(#"%#",dict);
if (!dict) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:AMLocalizedString(ServerResponceError, nil) forKey:#"error"];
block(dict);
return ;
}
block(dict);
}];
}

connection didReceiveData called twice while posting a Url in iphone?

I am new to iphone development.I have posted the URL with the user-name and password. I am able to print the data in "connection didReceiveData " method.But i see "connection didReceiveData" method called twice.I don't know ,where i am going wrong. Here is my code
- (void)viewDidLoad {
[super viewDidLoad];
NSString *post = [NSString stringWithFormat:#"&domain=school.edu&userType=2&referrer=http://apps.school.edu/navigator/index.jsp&username=%#&password=%#",#"xxxxxxx",#"xxxxxx"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://secure.school.edu/login/process.do"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"the data %#",string);
}
The whole HTML page is printed twice in the console.So please help me out.Thanks.
You may receive the response data in chunks, which is why NSURLConnection's documentation states:
"The delegate should concatenate the contents of each data object delivered to build up the complete data for a URL load."
Use an instance of NSMutableData for this and only process the complete data once you receive the -connectionDidFinishLoading: message.
As MacOS Developer Library states, connection:didReceiveData can be called multiple times if data is received in chunks. That means you have to save all the chunks in some variable and do data processing in connectionDidFinishLoading method. e.g.
NSMutableData *receivedData = [[NSMutableData alloc] init];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data, for example log:
NSLog(#"data: %#", [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]
}

iPhone API for Accessing Amazon S3 REST API

Does anyone have any suggestions for GETing from or POSTing to Amazon S3 services using their REST API via the iPhone. It does not look like it is possible but I may be reading the docs wrong.
Thank you in advance for your help!
L.
In a general case I'd recommend to use ASIHttpRequest, it has a lot of built-in functionality (REST compatible too) and a lot of things, making life easier than with NSURLConnection.
It also has S3 support out of box.
You should be able to use the NSURLRequest stuff to do what you want.
NSMutableData* _data = nil;
- (IBAction) doIt:(id)sender {
NSURL* url = [NSURL URLWithString: #"http://theurl.com/"];
NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: url];
NSURLConnection* con = [NSURLConnection connectionWithRequest: req delegate: self];
NSData* body = [#"body of request" dataUsingEncoding: NSUTF8StringEncoding];
_data = [NSMutableData new];
[req setHTTPMethod: #"POST"];
[req setHTTPBody: body];
[con start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_data appendData: data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString* result = [[[NSString alloc] initWithData: _data encoding: NSUTF8StringEncoding] autorelease];
// process your result here
NSLog(#"got result: %#", result);
}
This doesn't have any error checking in it and the _data variable should be stored in an instance variable, but the general idea should work for you. You will probably also need to set some request headers to tell the server what encoding the body data is in and so on.