Posting tweet with new api (1.1) in iOS - iphone

Since the twitter api is changed my app no longer posts tweet. Every thing was working fine before and according to new API only request pattern should change ? All the other stuff initialising the engine and rest should be same ?
And the method for sharing should be modified, so I modified it but getting "Bad Authentication 215". All the token info and other things I got it from the authentication header generated from twitter itself:
- (void) shareOnTwitter
{
NSString *urlString = [NSString stringWithFormat:#"https://api.twitter.com/1.1/statuses/update.json"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:#"check Check CHECK" forKey:#"status"];
[dict setValue:#"-- - - - - -" forKey:#"oauth_consumer_key"];
[dict setValue:#"- - - - - - -" forKey:#"oauth_nonce"];
[dict setValue:#"- - - - - - -" forKey:#"oauth_signature"];
[dict setValue:#"HMAC-SHA1" forKey:#"oauth_signature_method"];
[dict setValue:#"- - - - - - -" forKey:#"oauth_timestamp"];
[dict setValue:#"- - - - - - -" forKey:#"oauth_token"];
[dict setValue:#"1.0" forKey:#"oauth_version"];
NSString *jsonString = [dict JSONRepresentation];
NSData *jsonData = [NSData dataWithBytes:[jsonString UTF8String] length:jsonString.length];
[request setHTTPBody:jsonData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSLog(#"My request...%#", jsonString);
NSData *urlData;
NSURLResponse *response1;
NSError *error = nil;
urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response1 error:&error];
if(error)
{
NSLog(#"Error %#",error);
}
if(!urlData)
{
NSLog(#"No connection!");
}
NSString *responseStr = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#" Twitter : ... %#", responseStr);
}

Try below code. Its worked for me :
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
{
if (granted)
{
NSArray *accounts = [accountStore accountsWithAccountType:accountType];
if (accounts.count)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:#"check Check CHECK" forKey:#"status"];
NSString *retweetString = [NSString stringWithFormat:#"https://api.twitter.com/1.1/statuses/update.json"];
NSURL *retweetURL = [NSURL URLWithString:retweetString];
TWRequest *request = [[TWRequest alloc] initWithURL:retweetURL parameters:dict requestMethod:TWRequestMethodPOST];
request.account = [accounts objectAtIndex:0];
[request performRequestWithHandler:^(NSData *responseData1, NSHTTPURLResponse *urlResponse, NSError *error)
{
if (responseData1)
{
NSError *error1 = nil;
id response = [NSJSONSerialization JSONObjectWithData:responseData1 options:NSJSONReadingMutableLeaves error:&error1];
}
}];
}
}
}];

Twitter explained every thing in its new documentation from Authentication to loads of trivial things but no easy way for previous apps using 1.0 api, how to post a tweet or to upgrade.
Few changes to make it work (works for OAuth):
Open the MGTwitterEngine.m >
Make sure the macros are defined like this:
#define TWITTER_DOMAIN #"api.twitter.com/1.1"
#define HTTP_POST_METHOD #"POST"
#define TWITTER_SEARCH_DOMAIN #"search.twitter.com"
#define DEFAULT_CLIENT_VERSION #"1.0"
#if YAJL_AVAILABLE
#define API_FORMAT #"xml"
#import "MGTwitterStatusesYAJLParser.h"
#import "MGTwitterMessagesYAJLParser.h"
#import "MGTwitterUsersYAJLParser.h"
#import "MGTwitterMiscYAJLParser.h"
#import "MGTwitterSearchYAJLParser.h"
#else
#define API_FORMAT #"json"
#if USE_LIBXML
#import "MGTwitterStatusesLibXMLParser.h"
#import "MGTwitterMessagesLibXMLParser.h"
#import "MGTwitterUsersLibXMLParser.h"
#import "MGTwitterMiscLibXMLParser.h"
#else
#import "MGTwitterStatusesParser.h"
#import "MGTwitterUsersParser.h"
#import "MGTwitterMessagesParser.h"
#import "MGTwitterMiscParser.h"
#endif
#endif
You will be surprised that - (void) requestSucceeded: (NSString *) requestIdentifier and - (void) requestFailed: (NSString *) requestIdentifier withError: (NSError *) error will be called. But it is pretty easy to put a check that if succeeded is called than don't do anything in failed method.

Related

UITextField and NSURL URLWithString

I have built a translate application in ios. The application uses the Yandex translation api. I followed this tutorial: http://www.raywenderlich.com/5492/working-with-json-in-ios-5
My ViewController.m looks like this (I took out my api key):
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#import "ViewController.h"
#end
#interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress;
-(NSData*)toJSON;
#end
#implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress
{
NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: urlAddress] ];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
-(NSData*)toJSON
{
NSError* error = nil;
id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
// NSData* data = [[NSData dataWithContentsOfURL: TranslateText] ];
NSData*data = [NSURL URLWithString: [NSString stringWithFormat: #"https://translate.yandex.net/api/v1.5/tr.json/translate?key=apikeys&lang=en-es&text=%#", textfield.text]];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* TranslatedText = [json objectForKey:#"text"]; //2
NSLog(#"Text that was translated: %#", TranslatedText); //3
// 1) Get the latest loan
//NSDictionary* ttext = [TranslatedText objectAtIndex:0];
NSString* ttext = [TranslatedText objectAtIndex:0];
// 3) Set the label appropriately
humanReadble.text = [NSString stringWithFormat:#"%#",
//[ttext objectForKey:#"name"],
ttext];
}
#end`
When I run the app, I get the error Thread 1: signal SIGABRT on this line of code:
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
What should I do?
The error in your code is the use of the colon there. You should have the line be...
[NSURL URLWithString: [NSString stringWithFormat: #"https://translate.yandex.net/api/v1.5/tr.json/translate?apikeyes&text=%#", textfield.text];
Also, I do not know why you would do a #define. Grab the information in the method for handling the button getting pressed.
NSURL * translateURL = [NSURL URLWithString: [NSString stringWithFormat: #"https://translate.yandex.net/api/v1.5/tr.json/translate?apikeyes&text=%#", textfield.text];

Load Web-Content Asynchronously

I am trying to load web content asynchronously. I have a large amount of web calls in my viewdidappear method and my app is very unresponsive. I understand the concepts of synchronous and asynchronous loading of content, but don't know how to tell if this is being done asynchronously. The code below is simply embedded in my viewdidappear method, and I assume it is loading synchronously. How would I edit this to make it load asynchronously? Thank you all!
NSString *strURLtwo = [NSString stringWithFormat:#"http://website.com/json.php?
id=%#&lat1=%#&lon1=%#",id, lat, lon];
NSData *dataURLtwo = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURLtwo]];
NSArray *readJsonArray = [NSJSONSerialization JSONObjectWithData:dataURLtwo options:0
error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];
NSString *name = [element1 objectForKey:#"name"];
NSString *address = [element1 objectForKey:#"address"];
NSString *phone = [element1 objectForKey:#"phone"];
You can use NSURLConnectionDelegate:
// Your public fetch method
-(void)fetchData
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://website.com/json.php?id=%#&lat1=%#&lon1=%#",id, lat, lon]];
// Put that URL into an NSURLRequest
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
// Create a connection that will exchange this request for data from the URL
connection = [[NSURLConnection alloc] initWithRequest:req
delegate:self
startImmediately:YES];
}
Implement the delegate methods:
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// Add the incoming chunk of data to the container we are keeping
// The data always comes in the correct order
[jsonData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
// All data is downloaded. Do your stuff with the data
NSArray *readJsonArray = [NSJSONSerialization jsonData options:0 error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];
NSString *name = [element1 objectForKey:#"name"];
NSString *address = [element1 objectForKey:#"address"];
NSString *phone = [element1 objectForKey:#"phone"];
jsonData = nil;
connection = nil;
}
// Show AlertView if error
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
connection = nil;
jsonData = nil;
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
}
For asynchronous web content loading, I recommend you to use AFNetworking . It'll solve lots of your major headache of networking in future. How to do:
1) subclass AFHTTPCLient, for example:
//WebClientHelper.h
#import "AFHTTPClient.h"
#interface WebClientHelper : AFHTTPClient{
}
+(WebClientHelper *)sharedClient;
#end
//WebClientHelper.m
#import "WebClientHelper.h"
#import "AFHTTPRequestOperation.h"
NSString *const gWebBaseURL = #"http://whateverBaseURL.com/";
#implementation WebClientHelper
+(WebClientHelper *)sharedClient
{
static WebClientHelper * _sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:gWebBaseURL]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
return self;
}
#end
2) Request asynchronously your web content, put this code in any relevant part
NSString *testNewsURL = #"http://whatever.com";
NSURL *url = [NSURL URLWithString:testNewsURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operationHttp =
[[WebClientHelper sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *szResponse = [[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"Response: %#", szResponse );
//PUT your code here
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Operation Error: %#", error.localizedDescription);
}];
[[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];

how to use twitter user search api in MGTwitterengine iphone

I am using MGtwitterengine in iPhone , I want to use USER search API http://api.twitter.com/1/users/search.json?q={username} but I don't find any method for this in MGTwitterengine. how can I use this API in iphone to get users.
Thanks
Use like This :-
- (void)searchforTwUser {
OAToken *access_token = [[OAToken alloc] initWithKey:[tEngine oauthKey] secret:[tEngine oauthSecret]];
OAConsumer *aconsumer = [[OAConsumer alloc] initWithKey:kOAuthConsumerKey
secret:kOAuthConsumerSecret];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
NSString *spaceString=#" ";
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:self.searchName] invertedSet];
if ([spaceString rangeOfCharacterFromSet:set].location == NSNotFound)
{
NSString *Name = [self.searchName stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.twitter.com/1/users/search.json?q=%#",Name]];
NSLog(#"search name 1 is ..................................... %#",url);
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
consumer:aconsumer token:access_token realm:nil
signatureProvider:nil];
[request setHTTPMethod:#"GET"];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(searchTicket:didFinishWithData:)
didFailSelector:#selector(searchTicket:didFailWithError:)];
[request release];
}
else
{
NSString *addStr = #"%20";
NSString *firstCapChar = [[searchName substringToIndex:1] capitalizedString];
NSString *cappedString = [searchName stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.twitter.com/1/users/search.json?q=%#%#",cappedString,addStr]];
NSLog(#"search name 2 is ..................................... %#",url);
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
consumer:aconsumer token:access_token realm:nil
signatureProvider:nil];
[request setHTTPMethod:#"GET"];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(searchTicket:didFinishWithData:)
didFailSelector:#selector(searchTicket:didFailWithError:)];
[request release];
}
[access_token release];
[aconsumer release];
}
- (void) searchTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data {
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dict = [response objectFromJSONString];
NSLog(#"Dict %#",dict);
[twSearchArray removeAllObjects];
if (twSearchArray != nil) {
[twSearchArray release];
twSearchArray = nil;
}
twSearchArray = (NSMutableArray *)dict;
NSLog(#"Twitter %#",twSearchArray);
self.twLoaded = YES;
[twSearchArray retain];
[self prepareSearchResults];
[response release];
}
- (void) searchTicket:(OAServiceTicket *)ticket didFailWithError:(NSData *)error {
NSLog(#"Errors is %#",error.description);
}

Google Api Using With Json

When I Call Google API for get the address and i calling api here like .
-(void)searchviews:(NSString*)EditString selector:(SEL)sel
{
NSLog(#"Welcome To Search views");
searchviews=sel;
NSString *path =[NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false",EditString];
NSURL *url=[NSURL URLWithString:path];
NSLog(#"hiii---%#",url);
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request startAsynchronous];
[drkSignUp showWithMessage:nil];
NSLog(#" Complet--------------- ");
and for Request Method I call like .
- (void)requestFinished:(ASIHTTPRequest *)request {
//NSLog(#"%#",[request responseString]);
NSString *func = [self getFunc:[request url]];
NSLog(#"%#\n%#",func,[request responseString]);
if ([func isEqual:#"json?address=%#&sensor=false"])
{
NSDictionary *resDict = [parser objectWithString:[request responseString] error:nil];
NSLog(#"---- ResData%#",resDict);
NSString *result = [resDict objectForKey:#"successful"];
NSLog(#"hiiiii google api calling............");
[drkSignUp hide];
[self.delegate performSelector:searchviews withObject:[resDict objectForKey:#"results"]];
the is like that but problem create in fun . When i call
if ([func isEqual:#"json?address=%#&sensor=false"])
it is not calling cos the it is be Dynamic String.So What Should I put inplace of %# in func ?
You can fill the userInfo dictionary of ASIFormDataRequest like the following
//After this line
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
//Add
request.userInfo = [NSDictionary dictionaryWithObject:#"EditString" forKey:#"request"];
Then in
- (void)requestFinished:(ASIHTTPRequest *)request {
//Get the request userInfo
NSString *str = [request.userInfo objectForKey:#"request"];
//now fill the request string
NSString *requestString = [NSString stringWithFormat:#"json?address=%#&sensor=false", str];
//Check it with func
if ([func isEqual:requestString])
{
//Continue your procedure
}
}

Get driving direction in iPhone

I read both iPhone and Google Map for iPhone EULA and want to implement a static driving direction map in my iPhone application (native).
I am finding a simple way to get route data and display with build-in route display feature in iOS 4 SDK' Mapkit.
Is there any programmer implement a feature like this with Google Map and Bing Map? Since Bing Map provided routing data in SOAP web service, it's seem easier to programming driving direction with Bing's service.
I found the solution for this. Just use a JSON parser to got google map API
For example:
NSDictionary *testJsondata = [self testJson:GoogleMapXMLDirectionQueryString];
NSLog(#"Here is the title of the response: %#", [testJsondata valueForKey:#"status"]);
for (id key in testJsondata) {
NSLog(#"key: %#, value: %#", key, [testJsondata objectForKey:key]);
}
}
- (NSDictionary *) testJson : (NSString*) url
{
id response = [self objectWithUrl:[NSURL URLWithString:url]];
NSDictionary *feed = (NSDictionary *)response;
return feed;
}
- (id) objectWithUrl:(NSURL *)url
{
SBJsonParser *jsonParser = [SBJsonParser new];
NSString *jsonString = [self stringWithUrl:url];
// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSString *)stringWithUrl:(NSURL *)url
{
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse: &response
error: &error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
- (NSString *)getDirectionInXML:(NSString *)GoogleMapXMLDirectionQueryString
{
NSError *error;
NSURLResponse *response;
NSData *dataReply;
NSString *stringReply;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString: [NSString stringWithFormat:GoogleMapXMLDirectionQueryString]]];
[request setHTTPMethod: #"GET"];
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];
return stringReply;
}