I am working on an application that uses restful API call using prestashop API. I am new at IOS I coded the same method in android as:
InputStream is = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
/* adding credentials as it is RESTful call */
String username = "xyz";
String password = "";
client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),new UsernamePasswordCredentials(username, password));
// HTTP get request
HttpGet get = new HttpGet("http://www.example.com/api/");
HttpResponse responseGet;
responseGet = client.execute(get);
is = responseGet.getEntity().getContent();
} catch (ClientProtocolException e) {
Log.e("HTTP Request","Client Protocol exception" );
} catch (IOException e) {
Log.e("HTTP Request","IO exception" );
}
It is working perfectly for Android. For IOS I used this coding but I am not getting data from the server.
NSString *userName = #"XYZ";
NSString *password = #"";
//setting the string of the url taking from appliance IP.
NSString *urlString = #"http://www.example.com/api/";
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *str1 = [NSString stringWithFormat:#"%#:%#",userName,password];
NSLog(#" str1 %#", str1);
[request addValue:[NSString stringWithFormat:#"Basic %#",str1] forHTTPHeaderField:#"Authorization"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"str: %#", str);
please tell me what I am doing wrong and provide any solution.
Thanks!
You can build the URL string this way and it should work :-
NSString *str1 = [NSString stringWithFormat:#"http://%#:%##www.example.com/api",userName,password];
No need to use the HTTP header fields I believe
Username and password need to be encoded using Base64 encoding when using Basic HTTP authentication.
From Wikipedia's Article on that subject:
Client side
When the user agent wants to send the server authentication
credentials it may use the Authorization header.
The Authorization header is constructed as follows:[6] Username and
password are combined into a string "username:password"
The resulting string literal is then encoded using Base64
The authorization method and a space i.e. "Basic " is then put before
the encoded string. For example, if the user agent uses 'Aladin' as
the username and 'sesam open' as the password then the header is
formed as follows:
Authorization: Basic QWxhZGluOnNlc2FtIG9wZW4=
See this corrected code:
[...]
NSString *str1 = [NSString stringWithFormat:#"%#:%#",userName,password];
NSString *encodedString = [self stringByBase64EncodingWithString:str1];
[request addValue:[NSString stringWithFormat:#"Basic %#",encodedString] forHTTPHeaderField:#"Authorization"];
[...]
- (NSString *)stringByBase64EncodingWithString:(NSString *)inString
{
NSData *data = [NSData dataWithBytes:[inString UTF8String]
length:[inString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
NSUInteger length = [data length];
NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t *input = (uint8_t *)[data bytes];
uint8_t *output = (uint8_t *)[mutableData mutableBytes];
for (NSUInteger i = 0; i < length; i += 3)
{
NSUInteger value = 0;
for (NSUInteger j = i; j < (i + 3); j++)
{
value <<= 8;
if (j < length)
{
value |= (0xFF & input[j]);
}
}
static uint8_t const base64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
NSUInteger idx = (i / 3) * 4;
output[idx + 0] = base64EncodingTable[(value >> 18) & 0x3F];
output[idx + 1] = base64EncodingTable[(value >> 12) & 0x3F];
output[idx + 2] = (i + 1) < length ? base64EncodingTable[(value >> 6) & 0x3F] : '=';
output[idx + 3] = (i + 2) < length ? base64EncodingTable[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}
-(void)getApiCall:(NSString *)urlString response:(NSMutableArray *)response{
NSString *url= urlString;
NSURL * serviceUrl = [NSURL URLWithString:url];
NSMutableURLRequest * serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl cachePolicy:nil timeoutInterval:10.0];
[serviceRequest setValue:#"Application/json" forHTTPHeaderField:#"Content-type"];
[serviceRequest setHTTPMethod:#"GET"];
NSURLResponse *serviceResponse;
NSError *serviceError;
NSData *responseData = [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];
NSLog(#"REQUEST ==== >>>> %#",serviceUrl);
NSLog(#"RESPONSE ==== >>>> %#",responseData);
if (responseData != nil){
[self parseGetData:responseData responseArray:response];
}
else{
}
}
-(void)parseGetData:(NSData *)response responseArray:(NSMutableArray *)responseArray
{
id jsonObject = Nil;
NSString *charlieSendString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"ResponseString ==== >>>> %#",charlieSendString);
if (response==nil) {
NSLog(#"ERROR IN GET API....!!!!");
}else{
NSError *error = nil;
jsonObject =[NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
if (error)
{
NSLog(#"%#",error);
}
else
{
NSError *error = Nil;
jsonObject =[NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"Probably An Array");
}
else
{
NSLog(#"Probably A Dictionary");
NSDictionary *jsonDictionary=(NSDictionary *)jsonObject;
NSLog(#"jsonDictionary %#",[jsonDictionary description]);
if (jsonDictionary) {
[responseArray addObject:jsonDictionary];
}
}
}
}
}
Related
Is there is any way to create http listener in IOS
HttpListener: i mean, We will create a persistent http channel using Post request, the sever will push events to that channel. i want to create a channel that wait for server event.
-(void)httpPost:(NSString *)url andXml:(NSString *)xml{
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSURL *urls = [NSURL URLWithString:url];
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] initWithURL:urls];
NSData *postData = [xml dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *username =[[ApplicationStorage applicationStorage] userName];
NSString *password = [[ApplicationStorage applicationStorage] password];
//HTTP Basic Authentication
NSString *authenticationString = [NSString stringWithFormat:#"%#:%#", username, password];
NSData *authenticationData = [authenticationString dataUsingEncoding:NSUTF8StringEncoding];
NSString *authenticationValue = [authenticationData base64Encoding];
[request1 setValue:[NSString stringWithFormat:#"Basic %#", authenticationValue] forHTTPHeaderField:#"Authorization"];
[request1 setValue:#"text/xml" forHTTPHeaderField:#"Content-type"];
[request1 setHTTPMethod:#"POST"];
[request1 setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&response error:&error];
NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"httpPostOrPut >>>>>>>>> RESPONSE: %#",newStr);
// [[NSRunLoop currentRunLoop] run];
}
I have created the channel using above post request. but the channel close immediately after creation
i have done this in java
HttpResponse objBwResponse = bwPost(String.format(XML_CHANNEL_CREATION, generateChannelSetId()), getBWServerAddress() + CHANNEL_CREATION_URL);
if (objBwResponse != null && objBwResponse.getStatusLine() != null && objBwResponse.getStatusLine().getStatusCode() == 200) {
// success
Log.w(LOG_TAG, "XSI channel created succesfully");
InputStream content = objBwResponse.getEntity().getContent();
onChannelConnected(gChannelId);
processMessage(content);
} else {
// fail
Log.w(LOG_TAG, "error in creating channel response: "+objBwResponse+" status code: "+(objBwResponse!=null?objBwResponse.getStatusLine():"response null"));
}
private void processMessage(InputStream content) {
String responseXML;
Document documentXML;
in = new BufferedInputStream(content);
StringBuilder stringBuilder = new StringBuilder();
try {
int input;
**while ((input = in.read()) != -1) {**
stringBuilder.append((char) input);
if (stringBuilder.indexOf(CHANNEL_EVENT_MESSAGE_END_STRING) != -1) {
Thank you
Amith
I have an application where I have to create session using a URL and need to get cookie from that URL and pass the cookie to webview so that it won't ask for any username and password.
For that I am using this code:
- (void)getcookie {
NSURL* aUrl =
[NSURL URLWithString:#"https://www.sessioncheck.com/session/create"];
NSMutableURLRequest* request =
[NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
NSString* email = #"tina#gmail.com";
NSString* password = #"abcde#123";
NSString* combinedString =
[NSString stringWithFormat:#"%#:%#", email, password];
NSString* base64encodedstring =
[NSString stringWithBase64EncodedString:combinedString];
NSData* base64data = [NSData dataWithBase64EncodedString:combinedString];
[request addValue:[NSString stringWithFormat:#"Basic %#", base64encodedstring]
forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
NSError* error = nil;
NSData* returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:&error];
if (returnData != nil) {
NSDictionary* JSONDictionary =
[NSJSONSerialization JSONObjectWithData:returnData
options:kNilOptions
error:&error];
}
}
This is my Android code. I am able to get cookie in Android:
HttpGet get;
try {
get = new HttpGet(
new URI("https://www.sessioncheck.com/session/create"));
byte[] encodedBytes = Base64.encodeBase64((email+":"+password).getBytes());
//System.out.println("encodedBytes " + new String(encodedBytes));
get.setHeader("Authorization", "Basic " + new String(encodedBytes));
http.execute(get);
List<Cookie> cookies = ((DefaultHttpClient)http).getCookieStore().getCookies();
for (int i = 0; i < cookies.size(); i++) {
cookie = cookies.get(i);
}
String cookieString = cookie.getName() + "=" + cookie.getValue();
signedin.storeCookie("cookie", cookieString);
}
I am trying to get the base64encoded string from my combinedString(username:password) but the problem is my base64encodedstring is returning nil.
Did you use this code: https://github.com/nicklockwood/Base64 ?
If you did then you should use - (NSString *)base64EncodedString; instead.
So your code should look like this:
NSString* base64encodedstring = [combinedString base64EncodedString];
NSData* base64data = [base64encodedstring dataUsingEncoding:NSUTF8StringEncoding];
About cookies, you can get them from "returningResponse" outgoing parameter of -[NSURLConnection sendSynchronousRequest:returningResponse:error:].
You should pass an address of a NSHTTPURLResponse pointer into it.
So your code should be like this:
NSHTTPURLResponse *res = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&res
error:&error];
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[res allHeaderFields]
forURL:aUrl];
EDIT : As you requested, to set cookies into a NSMutableURLRequest, you have to use the NSArray *cookies from above. Here is the code:
// Use the cookies from the code above
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:newURL];
[req setAllHTTPHeaderFields:headers];
// Do your other setups here...
I have created a small project that can read and insert data from iPhone to sql server via RESTful WCF service.
I have read the data successfully with the following approach:
1- I have created a wcf web service that read data from Sql serverwith table Employees(firstname,lastname,salary):
"41.142.251.142/JsonWcfService/GetEmployees.svc/json/employees"
2- I have created a new project in xcode 5.0.2, and I added a textfield (viewData.text) to display data retrieved by the web service.
3- I added the following instruction in my viewController.m :
"#define WcfSeviceURL [NSURL URLWithString: #"41.142.251.142/JsonWcfService/GetEmployees.svc/json/employees"]"
3- In (void)viewDidLoad method, I implemented the below code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:WcfSeviceURL options:NSDataReadingUncached error:&error];
if(!error)
{
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
NSMutableArray *array= [json objectForKey:#"GetAllEmployeesMethodResult"];
for(int i=0; i< array.count; i++)
{
NSDictionary *empInfo= [array objectAtIndex:i];
NSString *first = [empInfo objectForKey:#"firstname"];
NSString *last = [empInfo objectForKey:#"lastname"];
NSString *salary = [empInfo objectForKey:#"salary"];
//Take out whitespaces from String
NSString *firstname = [first
stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *lastname = [last
stringByReplacingOccurrencesOfString:#" " withString:#""];
viewData.text= [viewData.text stringByAppendingString:[NSString stringWithFormat:#"%# %# makes $%#.00 per year.\n",firstname,lastname,salary]];
}
}
}
Check the following link : http://www.codeproject.com/Articles/405189/How-to-access-SQL-database-from-an-iPhone-app-Via.
As I mentioned, I can read the data from my iPhone without any problem.
So the second step is how to write and insert data from the iPhone to sql server.
for this, I created first the method that insert data in my webservice:
In WCF interface:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "json/InsertEmployee/{id1}/{id2}/{id3}")]
bool InsertEmployeeMethod(string id1,string id2, string id3);
In Implementation:
public bool InsertEmployeeMethod(string id1,string id2, string id3)
{
int success = 0;
using (SqlConnection conn = new SqlConnection("server=(local);database=EmpDB;Integrated Security=SSPI;"))
{
conn.Open();
decimal value= Decimal.Parse(id3);
string cmdStr = string.Format("INSERT INTO EmpInfo VALUES('{0}','{1}',{2})",id1,id2,value);
SqlCommand cmd = new SqlCommand(cmdStr, conn);
success = cmd.ExecuteNonQuery();
conn.Close();
}
return (success != 0 ? true : false);
}
So to test this web servcie method use:
"41.142.251.142/JsonWcfService/GetEmployees.svc/json/InsertEmployee/myName/MylastName/6565"
Then to consume this method from iPhone I used the following approach:
I decalared the Define Instruction:
"#define BaseWcfUrl [NSURL URLWithString:
#"41.142.251.142/JsonWcfService/GetEmployees.svc/json/InsertEmployee/{id1}/{id2}/{id3}"]"
Then I implemented the Insert Employee Method related to click button.
-(void) insertEmployeeMethod
{
if(firstname.text.length && lastname.text.length && salary.text.length)
{
NSString *str = [BaseWcfUrl stringByAppendingFormat:#"InsertEmployee/%#/%#/%#",firstname.text,lastname.text,salary.text];
NSURL *WcfServiceURL = [NSURL URLWithString:str];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:WcfServiceURL];
[request setHTTPMethod:#"POST"];
// connect to the web
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *respStr = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:respData
options:NSJSONReadingMutableContainers
error:&error];
NSNumber *isSuccessNumber = (NSNumber*)[json objectForKey:#"InsertEmployeeMethodResult"];
//create some label field to display status
status.text = (isSuccessNumber && [isSuccessNumber boolValue] == YES) ? [NSString stringWithFormat:#"Inserted %#, %#",firstname.text,lastname.text]:[NSString stringWithFormat:#"Failed to insert %#, %#",firstname.text,lastname.text];
}
}
But the issue here, is in the following instruction:
NSString *str = [BaseWcfUrl stringByAppendingFormat:#"InsertEmployee/%#/%#/%#",firstname.text,lastname.text,salary.text];
Always the system returns a message 'Data parameter nil' with this line, knowing that the firstname.text, and lastname.text, salary are all filled and I can see their values with NSLog(#"First Name :%#",firstname.text)...
Can you please help on this?
Thanks in advance.
I don't think NSURLs stringByAppendingFormat will do what you want.
Try something like this:
#define kBase_URL #"41.142.251.142/JsonWcfService/GetEmployees.svc/json/%#"
#define kAuthAPI_InsertEmployee_URL [NSString stringWithFormat:kBase_URL, #"InsertEmployee/%#/%#/%#"]
//Setup session
NSError *error;
NSURL *requestURL = [NSURL URLWithString:[NSString stringWithFormat:kAuthAPI_InsertEmployee_URL,firstname.text,lastname.text,salary.text]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:profileData options:0 error:&error];
[request setHTTPBody:postData];
etc. etc.
I need to update my app with Twitter API 1.1.
Previously I retrieved tweets using following URL:
http://search.twitter.com/search.json?tag=ios&rpp=25
But now it does not work.
I tried to use following URL from Twitter API documentation:
https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames&since_id=24012619984051000&max_id=250126199840518145&result_type=mixed&count=4.
But it returns the following error:
{"errors":[{"message":"Bad Authentication data","code":215}]}
How can I retrieve these tweets?
I would like to use Twitter.framework, but any suggestions will be appreciated.
I've found a solution. Twitter accepts two types of authentication for tweest retrieving:
Application-user authentication
Application-only authentication
The first type requires login and pass and the second does not require, but it requires bearer token.
At first my request looked in following way:
NSURL *URL = [NSURL URLWithString:#"http://search.twitter.com/search.json?tag=ios&rpp=25"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
Now it looks as follows:
if(self.bearerToken == nil) return;
NSURL *URL = [NSURL URLWithString:#"https://api.twitter.com/1.1/search/tweets.json?q=%%23ios&count=25"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
[urlRequest setValue:[NSString stringWithFormat:#"Bearer %#", self.bearerToken] forHTTPHeaderField:#"Authorization"];
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
Also this method requires to add two methods bearerToken and _base64Encode:
- (NSString *)bearerToken
{
if(_bearerToken == nil)
{
NSString * consumerKey = [config.consumerKey stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString * consumerSecret = [config.consumerSecret stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//the combined authentication key is "CONSUMER_KEY:CONSUMER_SECRET" run through base64 encoding.
//we'll use NSData instead of NSString here so that we can feed it directly to the HTTPRequest later.
NSString * combinedKey = [[self class] _base64Encode:[[NSString stringWithFormat:#"%#:%#", consumerKey, consumerSecret] dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://api.twitter.com/oauth2/token"]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:[NSString stringWithFormat:#"Basic %#", combinedKey] forHTTPHeaderField:#"Authorization"];
[urlRequest setValue:[NSString stringWithFormat:#"application/x-www-form-urlencoded;charset=UTF-8"] forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:[#"grant_type=client_credentials" dataUsingEncoding:NSUTF8StringEncoding]];
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
_bearerToken = [responseJSON valueForKey:#"access_token"];
}
return _bearerToken;
}
+(NSString *)_base64Encode:(NSData *)data{
//Point to start of the data and set buffer sizes
int inLength = [data length];
int outLength = ((((inLength * 4)/3)/4)*4) + (((inLength * 4)/3)%4 ? 4 : 0);
const char *inputBuffer = [data bytes];
char *outputBuffer = malloc(outLength);
outputBuffer[outLength] = 0;
//64 digit code
static char Encode[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
//start the count
int cycle = 0;
int inpos = 0;
int outpos = 0;
char temp;
//Pad the last to bytes, the outbuffer must always be a multiple of 4
outputBuffer[outLength-1] = '=';
outputBuffer[outLength-2] = '=';
/* http://en.wikipedia.org/wiki/Base64
Text content M a n
ASCII 77 97 110
8 Bit pattern 01001101 01100001 01101110
6 Bit pattern 010011 010110 000101 101110
Index 19 22 5 46
Base64-encoded T W F u
*/
while (inpos < inLength){
switch (cycle) {
case 0:
outputBuffer[outpos++] = Encode[(inputBuffer[inpos]&0xFC)>>2];
cycle = 1;
break;
case 1:
temp = (inputBuffer[inpos++]&0x03)<<4;
outputBuffer[outpos] = Encode[temp];
cycle = 2;
break;
case 2:
outputBuffer[outpos++] = Encode[temp|(inputBuffer[inpos]&0xF0)>> 4];
temp = (inputBuffer[inpos++]&0x0F)<<2;
outputBuffer[outpos] = Encode[temp];
cycle = 3;
break;
case 3:
outputBuffer[outpos++] = Encode[temp|(inputBuffer[inpos]&0xC0)>>6];
cycle = 4;
break;
case 4:
outputBuffer[outpos++] = Encode[inputBuffer[inpos++]&0x3f];
cycle = 0;
break;
default:
cycle = 0;
break;
}
}
NSString *pictemp = [NSString stringWithUTF8String:outputBuffer];
free(outputBuffer);
return pictemp;
}
Response has been changed too, so I had to change parser too.
Previous version:
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithString:jsonStr];
if (responseDictionary)
{
id data = responseDictionary[#"results"];
if ([data isKindOfClass:NSArray.class])
{
NSArray *dataArray = (NSArray*)data;
for (NSDictionary *post in dataArray)
{
avatarUrl = post[#"profile_image_url"];
author = post[#"from_user"];
message = post[#"text"];
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"EEE',' dd MMM yyyy HH:mm:ss ZZZZ"];
date = [inputFormatter dateFromString: post[#"created_at"]];
}
}
}
Current version:
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithString:jsonStr];
if (responseDictionary)
{
id data = [responseDictionary valueForKey:#"statuses"];
if ([data isKindOfClass:NSArray.class])
{
NSArray *dataArray = (NSArray*)data;
for (NSDictionary *post in dataArray)
{
avatarUrl = post[#"user"][#"profile_image_url"];
author = post[#"user" ][#"name"];;
message = post[#"text"];
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"EEE MMM dd HH:mm:ss ZZZZ yyyy"];
date = [inputFormatter dateFromString: post[#"created_at"]];
}
}
}
As per this doc it is not possible to fetch Hashtag feed without Authentication.
But you can manage it at server side. At server side you can Authenticate on Twitter and get the Hash tag feed from Twitter (Authenticate is also required here to get feed) . So Whenever user not Authenticate on iPhone that time you have to call Web Service and web Service will return the HashTag feed which you have manage at your server side code.
And If use already Authenticate on iOS Device (iPhone) than you can get the feed using iOS.
I'm making an app that requires you to login in. I"m using JSON. So far I've been able send a POST request with the Username and Password and I get a token back (it shows up in the console). When I don't enter in the correct username/password combination, I don't get a token back. What I would like to happen is to proceed to the next view controller if I get a token back. I think that I need to use an if statement (I'll put the code for switching view controllers into it) but I don't know what parameters I need in order to check if I get a token back.
Here is the code I'm using in the implementation file. It is in a method that runs when a button is pressed:
#try {
if([[usernameTextField text] isEqualToString:#""] || [[passTextField text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter both Username and Password" :#"Login Failed!"];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"username=%#&password=%#",[usernameTextField text],[passTextField text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"https://beta.network360.com/tokens"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(#"%#",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
NSLog(#"%d",success);
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self alertStatus:#"Logged in Successfully." :#""];
} else {
NSString *error_msg = (NSString *) [jsonData objectForKey:#"error_message"];
[self alertStatus:error_msg :#"Login Failed!"];
}
} else {
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#""];
}
}
}
#catch (NSException * e)
{
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#""];
//[[PSearchViewController new] performSegueWithIdentifier:#"loginCancel" sender:self];
}
Also, here is what I get in the console output when I put in the correct username/password combination (BTW I tried to change all the stuff that showed up in the console that was confidential, so if some stuff doesn't quite match, it should be fine. I just wanted to show that I get a token back):
2013-07-28 13:23:21.607 Empyrean[28283:c07] PostData: username=username#gmail.com&password=password
2013-07-28 13:23:22.300 Empyrean[28283:c07] Response code: 200
2013-07-28 13:23:22.301 Empyrean[28283:c07] Response ==> {"token":"scFDzxSAVk2sxQBShEGS","user":{"id":300230,"username":"username#gmail.com","display_name":"FirstName LastName","unconfirmed_email":null,"email":"username#gmail.com","confirmation_email":"username#gmail.com","client_identifier":null,"client_id":138,"is_admin":false,"support_email":"support#supportemail.com","application_name":"AppName","show_project_vintage_date":false,"is_anonymous":false,"is_active":true,"is_confirmed":true,"pending_reconfirmation":false,"can_resend_confirmation":false,"client_name":"Broker","show_advertisements":true,"header_logo":"/foo/headerlogo.gif","report_footer_logo":"/stuff/foo/footerlogo.png","authorized_features":["find_stuff","do_stuff","stuff_stuff","settings","menu","manage_stuff","measure_stuff","export_stuff"],"url":"https://www.website.com/stuff/numbersdsjkflds"}}
2013-07-28 13:23:22.304 Empyrean[28283:c07] {
token = dlsfkasdfDfdsklfdDsa;
user = {
"application_name" = "Application Name";
"authorized_features" = (
"find_stuff",
"do_stuff",
"stuff_stuff",
settings,
menu,
"manage_stuff",
"measure_stuff",
"export_stuff"
);
"can_resend_confirmation" = 0;
"client_id" = 138;
"client_identifier" = "<null>";
"client_name" = Broker;
"confirmation_email" = "username#gmail.com";
"display_name" = "FirstName LastName";
email = "username#gmail.com";
"url" = "https://www.website.com/stuff/numbersdsjkflds";
"header_logo" = "/foo/headerlogo.gif";
id = 300230;
"is_active" = 1;
"is_admin" = 0;
"is_anonymous" = 0;
"is_confirmed" = 1;
"pending_reconfirmation" = 0;
"report_footer_logo" = "/stuff/foo/footerlogo.png";
"show_advertisements" = 1;
"show_project_vintage_date" = 0;
"support_email" = "support#supportemail.com";
"unconfirmed_email" = "<null>";
username = "username#gmail.com";
};
}
NSDictionary *jsonData is a dictionary. Therefore, you can see if the token key exists.
if (jsonData[#"token"])
{
// Token exists, so move on.
[self.navigationController pushViewController:nextController animated:YES];
}
else
{
// Tell the user they messed it up.
}