how to use twitter user search api in MGTwitterengine iphone - 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);
}

Related

How to fetch LinkedIn connections/Friends/Contacts in iOS SDK?

I want to fetch all my friends from my LinkedIn profile. Please suggest me any tutorial.
My code is :
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/connections:(id,first-name,last-name,email-address,picture-url,Positions)"];
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
consumer:self.oAuthLoginView.consumer
token:self.oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(profileApiCallResult:didFinish:)
didFailSelector:#selector(profileApiCallResult:didFail:)];
You can use this for connections:For request part see this.
- (void)connectionsApiCallResult:(LOAServiceTicket *)ticket didFinish:(NSData *)data
{
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"connectionsApiCallResult====%#",responseBody);
[responseBody release];
}
- (void)connectionsApiCallResult:(LOAServiceTicket *)ticket didFail:(NSError *)error
{
NSLog(#"%#",[error description]);
}
-(void)GetConnectionsCall
{
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/connections:(headline,first-name,last-name,picture-url,id)"];
LOAMutableURLRequest *request =
[[LOAMutableURLRequest alloc] initWithURL:url
consumer:self.consumer
token:TestAccessToken
callback:nil
signatureProvider:nil];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
LOADataFetcher *fetcher = [[[LOADataFetcher alloc] init] autorelease];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(requestTokenResult:didFinish:)
didFailSelector:#selector(requestTokenResult:didFail:)];
}
Please try the following steps
first go to https://www.linkedin.com/secure/developer edit your App scope , make sure you have checked the r_network scope .
Then go to OAuthLoginView of you project , then go to -(void) requestTokenFromProvider method .
edit you scope in below lines .
OARequestParameter *nameParam = [[OARequestParameter alloc] initWithName:#"scope"
value:#"r_fullprofile+rw_nus+r_network"];
OARequestParameter * scopeParameter=[OARequestParameter requestParameter:#"scope"
value:#"r_fullprofile rw_nus r_network"];

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];

getting error when retrieving connections using linkedin api in iphone

I have an application where i am integrating linkedin in my app.I want to fetch the connections of the logged in user.For this i have done the code but it is returning error:
{
"errorCode": 0,
"message": "Unknown authentication scheme",
"requestId": "98TKWP0T23",
"status": 401,
"timestamp": 1355726431107
}
This is the code that i have done:-
(NSMutableArray*) getFriendsList
{
NSString *url1 = [NSString stringWithFormat:#"http://api.linkedin.com/v1/people/id=%#:(connections)?format=application/json",linkedinid];
NSLog(#"%#",url1);
NSURL *url = [NSURL URLWithString:url1];
OAMutableURLRequest *request = [[OAMutableURLRequest alloc]
initWithURL:url
consumer:consumer
token:token
callback:nil
signatureProvider:nil];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
[request setHTTPMethod:#"POST"];
NSError *err;
NSURLResponse *resp;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err];
NSMutableArray *arr = [[NSMutableArray alloc] init];
if (response != nil)
{
NSString *stringResponse = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *linkedin_response = [parser objectWithString:stringResponse error:nil];
}
}
but in the stringresponse it is returning the above mentioned error.
Try this :
- (void)getFriendsList
{
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/connections"];
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(networkApiCallResult:didFinish:)
didFailSelector:#selector(networkApiCallResult:didFail:)];
}
- (void)networkApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSDictionary *demo = [responseBody objectFromJSONString];
NSMutableArray *connections = [[NSMutableArray alloc] init];
for(int i=0;i<[[demo objectForKey:#"_count"] intValue];i++)
{
NSDictionary *person = [NSString stringWithFormat:#"%# %#",[[[[responseBody objectFromJSONString]
objectForKey:#"values"]
objectAtIndex:i]
objectForKey:#"firstName"],[[[[responseBody objectFromJSONString]
objectForKey:#"values"]
objectAtIndex:i]
objectForKey:#"lastName"]];
NSLog(#"Connection %d : %#",i,[NSString stringWithFormat:#"%# %#",[[[[responseBody objectFromJSONString]
objectForKey:#"values"]
objectAtIndex:i]
objectForKey:#"firstName"],[[[[responseBody objectFromJSONString]
objectForKey:#"values"]
objectAtIndex:i]
objectForKey:#"lastName"]]);
[connections addObject:person];
}
}
- (void)networkApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
NSLog(#"%#",[error description]);
}
From what it looks like, you are not passing up the "Username / Password" in the post, and as such you are getting the "Unknown authentication scheme". I am unsure if you would be able to detect in your own app the connections of the logged in user, unless you are storing their credentials inside your app.

Capturing PHP Response Through NSJSONSerialization

Hi I have this code here.
NSString *name = [[NSString alloc] initWithFormat:[nameField text]];
NSString *street = [[NSString alloc] initWithFormat:[streetField text]];
NSString *city = [[NSString alloc] initWithFormat:[cityField text]];
NSString *state = [[NSString alloc] initWithFormat:[stateField text]];
NSString *zip = [[NSString alloc] initWithFormat:[zipField text]];
NSString *urlToAuthPage = [[NSString alloc] initWithFormat:#"&name=%#&street=%#&city=%#&state=%#&zip=%#&lat=%#&lon=%#", name, street, city, state, zip, str1, str2];
NSData *postData = [urlToAuthPage dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d",[urlToAuthPage length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://yourlink.com/poop.php"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
NSError *error;
NSMutableArray *infoArray = (NSMutableArray*)[NSJSONSerialization JSONObjectWithData:postData options:kNilOptions error:&error];
NSLog(#"%#", [infoArray objectAtIndex:0]);
if (conn) {
UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Your party has been successfully posted" delegate:nil cancelButtonTitle:#"Close" otherButtonTitles: nil];
[successAlert show];
//NSLog(conn);
nameField.text = #"";
streetField.text = #"";
cityField.text = #"";
stateField.text = #"";
zipField.text = #"";
[nameField resignFirstResponder];
[streetField resignFirstResponder];
[cityField resignFirstResponder];
[stateField resignFirstResponder];
[zipField resignFirstResponder];
}
What I'm trying to do is get the response the server gives out that is in NSJon. I'm trying capture what is below. I've tried using an NSMutableArray to get it but it didn't work. What am I doing wrong?
{"status":1}
The problem is that NSJSONSerialization answers witha NSDictionary, not an NSMutableArray. You can't force it to be an array, since it needs a value and a key (in this case the key is "status" and the value is "1")

NSLocalizedDescription=Could not authenticate with OAuth.. error when using twitvid objective c library

I am using below code to upload image over twitvid site. but I am getting error
code to initialization.
- (void)awakeFromNib
{
[super awakeFromNib];
self.tv = [TwitVid twitVidWithSource:TwitVid_APP_ID
delegate:self];
}
Here is code to upload image.
- (NSString *)authenticationHeaderForKey:(NSString *)key secret:(NSString *)secret URL:(NSString *)URL
{
OAConsumer *consumer = [[OAConsumer alloc] initWithKey:OAUTH_CONSUMER_KEY
secret:OAUTH_CONSUMER_SECRET];
OAToken *token = [[OAToken alloc] initWithKey:key
secret:secret];
OAMutableURLRequest *theRequest = [[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]
consumer:consumer
token:token
realm:nil
signatureProvider:nil];
[consumer release];
[token release];
[theRequest prepare];
[theRequest autorelease];
return [theRequest valueForHTTPHeaderField:#"Authorization"];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *authHeader = [self authenticationHeaderForKey:OAUTH_TOKEN_KEY
secret:OAUTH_TOKEN_SECRET
URL:SERVICE_PROVIDER];
self.alertView = [[[UIAlertView alloc] initWithTitle:#"Uploading"
message:#"\n \n"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil] autorelease];
if ([[info valueForKey:UIImagePickerControllerMediaType] isEqualToString:(id)kUTTypeMovie]) {
//Video
self.alertView.title = #"Uploading Video";
NSString *mediaPath = [[info valueForKey:UIImagePickerControllerMediaURL] path];
self.uploadRequest = [tv uploadWithMediaFileAtPath:mediaPath
offset:0
message:#"Your message"
mediaID:nil
playlistID:nil
vidResponseParent:nil
userTags:nil
geoLatitude:nil
geoLongitude:nil
tags:nil
categoryID:nil
description:nil
title:nil
xVerifyCredentialsAuthorization:authHeader
xAuthServiceProvider:SERVICE_PROVIDER];
}
else {
//Picture
self.alertView.title = #"Uploading Picture";
UIImage *editedImage = [info valueForKey:UIImagePickerControllerEditedImage];
NSString *imagePath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"image.jpg"];
[[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];
[[NSFileManager defaultManager] createFileAtPath:imagePath
contents:UIImageJPEGRepresentation(editedImage, 0.8)
attributes:nil];
self.uploadRequest = [tv uploadPicWithMediaFileAtPath:imagePath
message:#"Your message"
mediaID:nil
userTags:nil
geoLatitude:nil
geoLongitude:nil
tags:nil
categoryID:nil
description:#"Image description"
title:#"Image title"
xVerifyCredentialsAuthorization:authHeader
xAuthServiceProvider:SERVICE_PROVIDER];
}
[self.alertView show];
[self dismissModalViewControllerAnimated:YES];
}
This is the exact code that provided by twitvid site. I only change my application name keys.
Now it is showing error as below
'uploadPic' REQUEST '1i1gc0hr' DID FAIL WITH ERROR: Error Domain=TVErrorBackendDomain Code=1001 "Could not authenticate with OAuth." UserInfo=0x18ca10 {NSLocalizedDescription=Could not authenticate with OAuth.}
Now I am confuse that there was no login for user. How this works?
Please help me to upload image or video on twitvid.
I am using this library: http://twitvid.pbworks.com/w/file/fetch/44841746/TwitVidSDK-iOS.zip
Thanks in advance.
Shivam
you have released the request already, either make it at class level i.e property or try this
OAMutableURLRequest *theRequest = [[[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]
consumer:consumer
token:token
realm:nil
signatureProvider:nil] autorlease];
return [theRequest valueForHTTPHeaderField:#"Authorization"];