JSON Response Displaying in alert vview? - iphone

Am new to iphone development i have a requirement like i need to show the JSON response in alert view (Eg:i have a login page when i give wrong details am getting a response from server i need to show the response in alert view)
here my code is
-(IBAction)signin:(id)sender{
requestSelect = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://abc....?"]];
NSString *requestString = [NSString stringWithFormat:#"request_parameter={\"EmailId\":\"%#\", \"Password\":\"%#\"}",email.text,password.text,nil];
NSLog(#"requestString in subarea %#",requestString);
NSMutableData *requestData =[NSMutableData dataWithBytes: [requestString UTF8String] length: [requestString length]];
[requestSelect setHTTPMethod: #"POST"];
[requestSelect setHTTPBody: requestData];
connection=[[NSURLConnection alloc] initWithRequest:requestSelect delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)response{
receiveddata = [[NSMutableData alloc]init ];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData{
[ receiveddata appendData:aData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
jsonString = [[NSString alloc] initWithData:receiveddata
encoding:NSUTF8StringEncoding];
dictServerData = [jsonString JSONValue];
valueForKey:#"result"]valueForKey:#"data"] objectAtIndex:0]valueForKey:#"service_status" ]);
arr_login= [[NSArray alloc]initWithArray:[[[[[dictServerData valueForKey:#"webservice"] valueForKey:#"result"]valueForKey:#"data"] objectAtIndex:0]valueForKey:#"service_status" ]];
objectForKey:#"webservice"]objectForKey:#"result"]objectForKey:#"data"]objectAtIndex:0]objectForKey:#"userdetails" ]objectAtIndex:0]);
NSMutableDictionary *DetailsDict=[NSMutableDictionary dictionaryWithObject:[ [[[[[dictServerData objectForKey:#"webservice"]objectForKey:#"result"]objectForKey:#"data"]objectAtIndex:0]objec tForKey:#"userdetails" ]objectAtIndex:0] forKey:#"data"];
NSLog(#"details dict : %#",DetailsDict);
defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:DetailsDict forKey:#"details"];
UpdateDetail *updt =[[UpdateDetail alloc]initWithNibName:#"UpdateDetail" bundle:Nil];
[self.navigationController pushViewController:updt animated:YES];
[updt release];
}

If you just want to show an alert view with a message do the following :
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Your Title"
message: #"Your message"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
This will open a modal alert view (i.e. No touches are passed trough it until you tap the OK) button.
So just put the JSON response in the message (Convert it to a readable string if needed)

Related

Sharing a video URL in LinkedIn integration in iPhone

We can share a message(text) through LinkedIn integration in iPhone Apps. Also, I can share an image Url in LinkedIN ,but Is there any possibility to share a video url through LinkedIn in iPhone Apps......?
Thanks In Advance.....
Use MIS-LinkedIn-Share for sharing url.
Just write following code to share.
- (IBAction)share:(id)sender {
[[MISLinkedinShare sharedInstance] shareContent:self postTitle:#"Title" postDescription:#"Description" postURL:#"http://www.youtube.com/watch?v=_FaWTNEyG80" postImageURL:#"http://www.google.com/images/errors/logo_sm.gif"];
}
don't forget to set api and secret key before sharing.
OR
you can also use method with oAuthStarterkit to share url :-
Here is working code for oAuthStarterKit
1) Open the file OAuthLoginView.m
2) Find the method initLinkedInApi, add your api and secret keys here.
3)Comment lines on viewDidAppear in OAuthLoginView as
- (void)viewDidAppear:(BOOL)animated
{
if ([apikey length] < 64 || [secretkey length] < 64)
{
// UIAlertView *alert = [[UIAlertView alloc]
// initWithTitle: #"OAuth Starter Kit"
// message: #"You must add your apikey and secretkey. See the project file readme.txt"
// delegate: nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil];
// [alert show];
// [alert release];
//
// // Notify parent and close this view
// [[NSNotificationCenter defaultCenter]
// postNotificationName:#"loginViewDidFinish"
// object:self
// userInfo:self.profile];
// [self dismissModalViewControllerAnimated:YES];
}
[self requestTokenFromProvider];
}
- (void)shareImp
{
NSLog(#"share Imp called ");
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/shares"];
OAMutableURLRequest *request =[[OAMutableURLRequest alloc] initWithURL:url
consumer:consumer
token:self.accessToken
callback:nil
signatureProvider:nil];
NSMutableDictionary *contents=[[NSMutableDictionary alloc] init];
[contents setValue:#"description goes here" forKey:#"description"];
[contents setValue:#"www.google.com" forKey:#"submitted-url"];
[contents setValue:#"title goes here" forKey:#"title"];
[contents setValue:#"http://economy.blog.ocregister.com/files/2009/01/linkedin-logo.jpg" forKey:#"submitted-image-url"];
NSMutableDictionary *visible=[[NSMutableDictionary alloc] init];
[visible setValue:#"anyone" forKey:#"code"];
NSMutableDictionary *updatedic=[[NSMutableDictionary alloc] init];
[updatedic setObject:visible forKey:#"visibility"];
[updatedic setObject:contents forKey:#"content"];
[updatedic setValue:#"Check out the LinkedIn Share API!" forKey:#"comment"];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:updatedic forKey:#"share"];
[archiver finishEncoding];
[archiver release];
NSLog(#"post dictionary is %#",updatedic);
NSData *postData=[NSData dataWithData:data];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d",[postData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[request setHTTPMethod:#"POST"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(postUpdateApiCallResult:didFinish:)
didFailSelector:#selector(postUpdateApiCallResult:didFail:)];
[request release];
}
- (void)postUpdateApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
NSLog(#"did finish called ");
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"response body after posting is %#",responseBody);
[responseBody release];
[self dismissModalViewControllerAnimated:YES];
}
- (void)postUpdateApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
NSLog(#"%#",[error description]);
}
By using Sharekit frame work we are able to post the video URL in LinkedIn.for that we can pass url as a string,
SHKItem *shareItem = [SHKItem text:text];
[SHKLinkedIn shareItem:shareItem];

POST username and password in JSON

I have a web service I am working with a url such as
//myurl/index.jsp?user_name=bob&user_pwd=new
as you can see the username has been set as "bob" and password "new". The site give this json file when entered,
[{"success":"1"}]
How do you implemented it on xcode, where when a user enters "bob" as username and "new" as password it should lead to the next controller. How do can I achieve that ?
I followed this tutorial though it's not quite the same, how do you do this. Thanks.
Use a navigation controller and set you view controller as the rootViewController. Then after the user has entered the credentials push the new view controller onto the navigation stack.
Get the value of success from json response. If it is equal to 1 then push to next controller else do nothing.
In Following code you can pass data by either GET or POST method … use any one (As You Wish)
-(void) sendRequest
{
//////////////////////////// GET METHOD /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
NSString *strURL=[NSString stringWithFormat:#"http://myurl/index.jsp?user_name=bob&user_pwd=new"];
self.request=[NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];
self.nsCon=[[NSURLConnection alloc] initWithRequest:request delegate:self];
//////////////////////////// POST METHOD /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
NSString *postString = [NSString stringWithFormat:#"&user_name=bob&user_pwd=new"];
NSString *url = [NSString stringWithFormat:#"http://myurl/index.jsp/"];
self.request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[self.request setHTTPMethod:#"POST"];
[self.request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(self.nsCon)
{
self.receivedData=[[NSMutableData alloc] init];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Error",#"") message:NSLocalizedString(#"Not Connected !!",#"") delegate:nil cancelButtonTitle:NSLocalizedString(#"OK",#"") otherButtonTitles:nil];
[alert show];
[alert release];
}
}
#pragma mark -
#pragma mark - Connection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[GeneralClass stopHUD];
NSLog(#"Connection failed.");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Error",#"") message:NSLocalizedString(#"Connection failed!",#"") delegate:nil cancelButtonTitle:NSLocalizedString(#"OK",#"") otherButtonTitles:nil];
[alert show]; alert = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *receivedData = [responseString JSONValue];
if([[receivedData objectForKey:#"success"] isEqualToString:#"1"])
{
MainDetailViewController *mdController = [[MainDetailViewController alloc] init];
[self.navigationController pushViewController:mdController animated:YES];
}
else
{
NSLog(#"%#",receivedData);
}
}
Post login data
NSString *soapMsg = [NSString stringWithFormat:#"&data={\"LoginUser\":[{\"UserName\":\"%#\",\"Password\":\"%#\"}]}",firstname.text, password.text];
NSHTTPURLResponse *response;
NSData *myRequestData = [ NSData dataWithBytes: [ soapMsg UTF8String ] length: [ soapMsg length ] ];
NSString *postLength = [NSString stringWithFormat:#"%d", [myRequestData length]];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:#"http://myurl/index.jsp"]];
[request setHTTPMethod: #"POST" ];
[request setHTTPBody: myRequestData ];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: myRequestData];
NSURLConnection *myConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
Receive and vaild json data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:WebXmlData encoding:NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue];
BOOL success = [[results objectForKey:#"success"] boolValue];
if (success) {
ViewController *viewController =[[ViewController alloc]initWithNibName:#"ViewController" bundle:nil];
[self.navigationController pushViewController:viewController animated:YES];
}
}
Not quite the answer you are looking for but this is more a recommendation for what should you use.
I use github link for Network related activities.
They have nice documentation and very easy to use (uses blocks)
NSDictionary *paramsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"user",#"client_id",#"password",#"new", nil];
[[YourAFHttpClientExtenstion sharedInstance] postPath:LOGIN_PATH parameters:paramsDictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {
//handle success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// handle error.
}];
YourAFHttpClientExtenstion is extending AFHttpClient and adds a convening method of shared instance and implements initWithBaseUr:

Web service request in Objective C

I am new in objective C. I have done app in j2me and android using below code. I m trying same to consume web service through objective C but not getting success. It will be great if anyone guide me.
Thanks.
public static String RetriveData(String myStr)
{
String result1 = "-1";
Object ob1 = new Object();
ob1 =MyStr;
SoapObject rpc = new SoapObject("http://abcd.com/", "MyMethod");
rpc.addProperty("Mystr", ob1.toString());
try
{
Object strdata = new HttpTransport("http://11.22.33.44/myService.asmx", "http://abcd.com/" + "MyMethod").call(rpc);
result1 = strdata.toString().trim();
}
catch (Exception ex)
{
System.out.println("In catch block :" +ex);
}
return result1;
}
I am trying same through objective C as below but getting error.
NSURL *url = [NSURL URLWithString:#"http://11.22.33.44/MyService.asmx"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
//
//[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://abcd.com/MyMethod" forHTTPHeaderField:#"SOAPAction"];
//[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest addValue:#"MyStr" forHTTPHeaderField:#"MyStr"];
[theRequest setHTTPMethod:#"POST"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}
[nameInput resignFirstResponder];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction");
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:
[webData length] encoding:NSUTF8StringEncoding];
NSLog(theXML);
[theXML release];
if( xmlParser )
{
[xmlParser release];
}
xmlParser = [[NSXMLParser alloc] initWithData: webData];
[xmlParser setDelegate: self];
[xmlParser setShouldResolveExternalEntities: YES];
[xmlParser parse];
[connection release];
[webData release];
}
My personal recommendation is to use ASIHttpRequest. I consume web services (both .NET and PHP) with it and it seems much easier and straightforward to use in most cases.
Just include the ASIHttpRequest classes and the MBProgressHUD (If you want to use it)
Here is what I use to do it:
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Connecting to Server";
// Start request
NSURL *url = [NSURL URLWithString:#"http://mydomain/MyWebService.asmx/MyMethod"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setValidatesSecureCertificate:NO];
// Now setup the Request
[request setPostValue:#"MyValue1" forKey:#"WebServiceArg1"];
[request setPostValue:#"MyValue2" forKey:#"WebServiceArg2"];
[request setDelegate:self];
[request startAsynchronous];
Now use the delegate methods to check and consume the response from the web service:
#pragma mark - ASIHttpRequest Delegate Methods
- (void)requestFinished:(ASIHTTPRequest *)request
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
if (request.responseStatusCode == 200) {
NSString *responseString = [request responseString];
// Do something with this, create an array or dictionary depending on how the return data is structured (this assumes you are using a JSON formatted return string btw
}
else {
// Standard UIAlert Syntax
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:#"Connection Error"
message:#"My Message"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[myAlert show];
}
} else {
NSLog(#"Error finishing request");
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
// Standard UIAlert Syntax
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:#"Connection Error"
message:#"Unable to establish connection"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[myAlert show];
NSError *error = [request error];
NSLog(#"%#",error.localizedDescription);
}
There are many ways to do it but this is what I would use.

How to twit a picture with some text in iPhone

I want to know that is there any way I can post picture in twitter with some text, some one has suggested to use "http://tinyurl.com/".I don't know where to start, in my previous application I twit successfully but that only contains text.
A proper direction to proceed would be a great help.
There are a couple of ways. I would suggest you use ShareKit. It does most of the work for you.
To post image to twitter we have to first post the image to twit pick and then we have to send that url to twitter that is the process to send image to twitter this is the sample code to send image to twitter..........
NSString *postUrl = #"https://api.twitter.com/1/statuses/update.json";
ASIFormDataRequest *request = [[ASIFormDataRequest alloc]
initWithURL:[NSURL URLWithString:postUrl]];
NSMutableDictionary *postInfo = [NSMutableDictionary
dictionaryWithObject:statusText.text
forKey:#"status"];
NSLog(#"%#",postInfo);
NSString *str1= statusText.text;
NSLog(#"Status posted. HTTP result code: %d", request.responseStatusCode);
[request release];
[statusText resignFirstResponder];
ASIFormDataRequest *req = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:#"http://api.twitpic.com/2/upload.json"]];
[req addRequestHeader:#"X-Auth-Service-Provider" value:#"https://api.twitter.com/1/account/verify_credentials.json"];
[req addRequestHeader:#"X-Verify-Credentials-Authorization"
value:[oAuth oAuthHeaderForMethod:#"GET"
andUrl:#"https://api.twitter.com/1/account/verify_credentials.json"
andParams:nil]];
[req setData:UIImageJPEGRepresentation(imageView.image, 0.8) forKey:#"media"];
// Define this somewhere or replace with your own key inline right here.
[req setPostValue:#"74734e805f2ad85afae441ca12c16087" forKey:#"key"];
[req startSynchronous];
NSLog(#"Got HTTP status code from TwitPic: %d", [req responseStatusCode]);
NSLog(#"Response string: %#", [req responseString]);
NSDictionary *twitpicResponse = [[req responseString] JSONValue];
NSLog(#"%#",[[req responseString] JSONValue]);
textView.text = [NSString stringWithFormat:#"Posted image URL: %#", [twitpicResponse valueForKey:#"url"]];
NSString *str=[NSString stringWithFormat:#" %#",[twitpicResponse valueForKey:#"url"]];
NSLog(#"%#",str);
if([str isEqualToString:#" (null)"])
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Message" message:#"Could not authenticate you(header rejected by twitter)" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
}
else
{
NSString *postUrl = #"https://api.twitter.com/1/statuses/update.json";
ASIFormDataRequest *request = [[ASIFormDataRequest alloc]
initWithURL:[NSURL URLWithString:postUrl]];
NSString *txtmessage=[str1 stringByAppendingString:str];
/*NSMutableDictionary *postInfo = [NSMutableDictionary
dictionaryWithObject:[twitpicResponse valueForKey:#"url"]
forKey:#"status"];*/
NSMutableDictionary *postInfo = [NSMutableDictionary
dictionaryWithObject:txtmessage
forKey:#"status"];
for (NSString *key in [postInfo allKeys]) {
[request setPostValue:[postInfo objectForKey:key] forKey:key];
}
[request addRequestHeader:#"Authorization"
value:[oAuth oAuthHeaderForMethod:#"POST"
andUrl:postUrl
andParams:postInfo]];
[request startSynchronous];
if(request.responseStatusCode!=200)
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Message" message:#"Already posted" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
}
else {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Message" message:#"sucess" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
}
NSLog(#"Status posted. HTTP result code: %d", request.responseStatusCode);
statusText.text = #"";
[request release];
[statusText resignFirstResponder];
}

Uploading video file to the URL

I am trying to upload video file to the specified URL. When I press button video file should upload into the URL which I used. But no response is coming.
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"3idiots" ofType:#"mov"];
NSURL *uploadurl=[NSURL URLWithString:#"http://115.111.27.206:8081/vblo/upload.jsp"];
//NSData *postVideoData = [NSData dataWithContentsOfFile:filePath];
NSData *postVideoData = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postVideoLength = [NSString stringWithFormat:#"%d", [postVideoData length]];
NSMutableURLRequest *request12 = [[[NSMutableURLRequest alloc] init] autorelease];
[request12 setURL:uploadurl];
[request12 setHTTPMethod:#"POST"];
[request12 setValue:postVideoLength forHTTPHeaderField:#"Content-Length"];
[request12 setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request12 setHTTPBody:postVideoData];
NSURLConnection *theConnection12 = [[NSURLConnection alloc] initWithRequest:request12 delegate:self];
if( theConnection12 )
{
webData12 = [[NSMutableData data] retain];
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData12 setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData12 appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus12 = [[NSString alloc] initWithBytes: [webData12 mutableBytes] length:[webData12 length] encoding:NSUTF8StringEncoding];
NSLog(loginStatus12);
if(loginStatus12)
{
UIAlertView *statusAlert12 = [[UIAlertView alloc]initWithTitle:nil message:(NSString *)loginStatus12 delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[statusAlert12 show];
}
}
you need to send the request, add this line after you set the HTTPBody
NSData *serverReply = [NSURLConnection sendSynchronousRequest: request12 returningResponse:&response error:&error];