I am using push notification in my iOS app.
I cant able to get the push notification message from the server. But i can get the message when using third party server APN Tester free.
In my app i am using backend as .net webservice (i.e asmx file). Below are the code i am using for push notification.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
NSLog(#"didFinishLaunchingWithOptions");
return YES;
}
/-(void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(#"My token is: %#", deviceToken);
NSString *deviceTokenString = [NSString stringWithFormat:#"%#", deviceToken];
NSLog(#"didRegisterForRemoteNotificationsWithDeviceToken");
NSLog(#"My token is: %#", deviceTokenString);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:deviceTokenString
message:#"devicetoken"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
/
}*/
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(#"My token is: %#", deviceToken);
_token_data =deviceToken;
NSString *title = [NSString stringWithFormat:#"%#",_token_data];
NSString *trimmedString = [title stringByReplacingOccurrencesOfString: #" " withString:#""];
trimmedString = [trimmedString stringByReplacingOccurrencesOfString: #"<" withString:#""];
trimmedString = [trimmedString stringByReplacingOccurrencesOfString: #">" withString:#""];
_tokenkey = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];
NSString *soapFormat = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<soap:Envelope xmlns:xsi=\"http:/
"<soap:Body>\n"
"<AddAppleDeviceToken xmlns=\"http:/
"<PortalId>0</PortalId>\n"
"<ModuleId>12</ModuleId>\n"
"<strDeviceToken>sdfssdfs</strDeviceToken>\n"
"</AddAppleDeviceToken>\n"
"</soap:Body>\n"
"</soap:Envelope>\n"];
NSURL *locationOfWebService = [NSURL URLWithString:#"http://www.mywebsite.com/push.asmx"
wsDeviceToken.asmx"];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc]initWithURL:locationOfWebService];
NSString *msgLength = [NSString stringWithFormat:#"%lu",(unsigned long)[soapFormat length]];
[theRequest addValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue:#"http:/
[theRequest addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
/
[theRequest setHTTPBody:[soapFormat dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connect = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
NSLog(#"soapFormat %#",soapFormat);
if (connect) {
_webData = [[NSMutableData alloc]init];
NSLog(#"Connection Establish");
}
else {
NSLog(#"No Connection established");
}
NSString * test = [NSString stringWithFormat:#"Your Device token is %#", trimmedString];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:test
message:#"devicetoken"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
if (notificationSettings.types != UIUserNotificationTypeNone) {
NSLog(#"didRegisterUser");
[application registerForRemoteNotifications];
UIAlertView *alert33 = [[UIAlertView alloc] initWithTitle:#"didRegisterUser"
message:#"didRegisterUser"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert33 show];
}
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
NSLog(#"Failed to get token, error: %#", error);
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
/
/
NSString *message = [[userInfo objectForKey:#"aps"]
objectForKey:#"alert"];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#""
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
/
}
#pragma - NSURLConnection delegate method
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[_webData setLength: 0];
NSHTTPURLResponse * httpResponse;
httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"HTTP error %zd", (ssize_t) httpResponse.statusCode);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{ NSLog(#"DONE. Received Bytes: %lu", (unsigned long)[_webData length]);
self.xmlParser = [[NSXMLParser alloc]initWithData:_webData];
[self.xmlParser setDelegate: self];
[self.xmlParser parse];
}
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *) attributeDict {
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"AddAppleDeviceTokenResult"]) {
NSString *tmpstr = [[NSString alloc] init];
tmpstr = [tmpstr stringByAppendingString:soapResults];
[soapResults setString:#""];
NSLog(#"AddAppleDeviceTokenResult %#",tmpstr);
if([tmpstr isEqualToString:#"DeviceToken Added in Database"])
{
NSString * test = [NSString stringWithFormat:#"Your Device token is added in database"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:test
message:_tokenkey
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
NSLog(#"Token added successfully");
[[NSUserDefaults standardUserDefaults]setValue:#"1" forKey:#"isDeviceTokenAdded"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
}
}
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string {
if (!soapResults) {
/
soapResults = [[NSMutableString alloc] init];
NSLog(#"soapResults %#",soapResults);
}
if([string length] > 0){
NSString *cleanString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if([cleanString length] >0){
[soapResults appendString: string];
}
}
}
Any suggessions Please.
Thanks in advance.
jejai Replace This Method
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSString *message = [[userInfo objectForKey:#"aps"]
objectForKey:#"alert"];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#""
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
TO
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler
{
NSString *message = [[userInfo objectForKey:#"aps"]
objectForKey:#"alert"];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#""
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
Related
I am new to IOS i want to display response from post in alert view.in nslog i showed response. i need when i clicked button alert view can display my response.
coding:
-(void) sendDataToServer : (NSString *) method params:(NSString *)str{
NSData *postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[str length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];
NSLog(#"%#",str);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
mutableData = [[NSMutableData alloc]init];
}
}
alerview:
- (IBAction)butt1:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Value"
message:#"%#"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"ok", nil];
[self sendDataToServer :#"POST" params:str];
[alert show];
}
post method delegates:
here i get response in json111 that i showed in nslog successfully but in alert view i failed
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError* error111;
json111 = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error111];
NSLog(#"%#",json111);
}
[![emptyvalue in alertview][1]][1]
change this into
updated answer
#interface myViewController : UIViewController <UIAlertViewDelegate>
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError* error111;
json111 = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error111];
NSLog(#"%#",json111);
NSArray *temp = [ json111 objectForKey:#"Currencies"];
// you can directly fetch like
NSDictionary *fetchDict = [temp objectAtIndex:0];
NSDictionary *fetchUnit = [temp objectAtIndex:1];
// finally you can fetch like
NSString * total = [fetchDict objectForKey:#"total"];
NSString * one_unit = [fetchUnit objectForKey:#"one_unit"];
//updated
NSString *final = [NSString stringWithFormat:#"%# , %#", total,one_unit];
// in here you can assign the value to Alert
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Value"
message:final
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"ok", nil];
alert.tag = 100;
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 100)
{
if (buttonIndex == 0)
{
// ok button pressed
//[self sendDataToServer :#"POST" params:str];
}else
{
// cancel button pressed
}
}
You should know the basics of NSString, refer here.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Value"
message:[NSString stringWithFormat:#"%#", str]
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"ok", nil];
You can save your response in an NSString and then pass this string in the message field of your alert view.
However, as of iOS 8,
UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead
Change your Alert View as following :
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Value"
message:[NSString stringWithFormat:#"Response Message : %#",str]
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"ok", nil];
This will display your response message instead %#..
If you want to send Data to Server on Click on alertView, you need to write code in alertView Delegate clickedButtonAtIndex
Hope it helps..
hi i am giving reference link of stack over flow
How to update Google Maps marker position in swift/iOS
You can try the online swift to objective c converters. Like
http://objc2swift.me
These converts are used to convert objective c to Swift. I know you want to convert Swift to objective C. But I think you can learn some think to here. Just write the code. Swift is very similar to objective c.Only difference in syntax. You can understand very easily.
*Stack Overflow not for Writing Codes. If you have any Problem in codes. We will help you.
Here is the code, Create a button, add selector to that button. Hope you will set your google map.
NSMutableData *webData;
#property NSURLConnection *connection;
-(void) getResult //call this in button selector
{
marker=nil; //create a GMSMarker globally.
[self.mapView clear];
NSString *strUrl = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%#&type=atm&sensor=true&name=%#&key=%#",latitude,longitude,_radius.text,_searchTxt.text,googleAPI_Key ];
[self addMarkerDataUrl:strUrl];
}
-(void)addMarkerDataUrl:(NSString *)urlString
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString* urlTextEscaped = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlTextEscaped]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
[request setHTTPMethod: #"GET"];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(self.connection)
{
webData = [[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (webData)
{
[self gettingData:webData ];
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
webData=nil;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#" response %d",kCFURLErrorNotConnectedToInternet);
if ([error code] == kCFURLErrorNotConnectedToInternet)
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:#"No Connection Error"
forKey:NSLocalizedDescriptionKey];
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:userInfo];
NSLog(#"error %#",noConnectionError);
[self handleError:noConnectionError];
}
else
{
[self handleError:error];
}
self.connection = nil;
[self errorInConnection];
}
- (void)handleError:(NSError *)error
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"SUBCOMMUNE" message:#"Timed Out" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
-(void)errorInConnection
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Try again after some time" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
- (void) gettingData:(NSData *)data
{
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray* places = [json objectForKey:#"results"];
NSLog(#"Google Data: %#", places);
tempArray = [[NSMutableArray alloc]init];
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if([[NSString stringWithFormat:#"%#",[allDataDictionary objectForKey:#"status"]]isEqualToString:#"OK"])
{
collectionArray =[[NSMutableArray alloc]init];
locArray = [[NSMutableArray alloc]init];
NSMutableArray *legsArray = [[NSMutableArray alloc] initWithArray:allDataDictionary[#"results"]];
for (int i=0; i< [legsArray count]; i++)
{
[collectionArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:legsArray[i][#"icon"],#"icon", legsArray[i][#"name"],#"name",legsArray [i][#"vicinity"],#"vicinity",legsArray[i][#"id"],#"id",nil]];
[locArray addObject:legsArray[i][#"geometry"][#"location"]];
[tempArray addObject:legsArray[i][#"vicinity"]];
}
NSLog(#"CollectionArray =%#",collectionArray);
NSLog(#"LocationArray =%lu",(unsigned long)locArray.count);
[self addMarkers];
}
else
{
NSString *msg=[allDataDictionary objectForKey:#"error_message"];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Error !\n Check Radius or ATM Name" message:msg delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
-(void)addMarkers
{
for(int i=0;i<locArray.count;i++)
{
starting = [NSMutableDictionary dictionaryWithObjectsAndKeys:locArray[i][#"lat"],#"lat",locArray[i][#"lng"],#"lng", nil];
name = [NSMutableDictionary dictionaryWithObjectsAndKeys:collectionArray[i][#"name"],#"name",nil];
CLLocationCoordinate2D position = CLLocationCoordinate2DMake([[starting objectForKey:#"lat"] doubleValue] , [[starting objectForKey:#"lng"] doubleValue]);
marker1 = [GMSMarker markerWithPosition:position];
GMSCameraUpdate *updatedCamera=[GMSCameraUpdate setTarget:CLLocationCoordinate2DMake(latitude, longitude) zoom:15];
[self.mapView animateWithCameraUpdate:updatedCamera];
marker1.title = [name objectForKey:#"name"];
[marker1 setIcon:[UIImage imageNamed:#"Map Pin-48.png"]];
marker1.appearAnimation = YES;
marker1.map = self.mapView;
}
}
I implement the push notification for ios.But the device token is get for ipad ,ios v 8.3 but when i install the app in iphone 6s plus v9.0 then deveice token is not registerd.I create the all certificate according to this reference but i get the notification in ipad but not get iphone .
So what is the problem.I can not find out.Please help me
if(IS_OS_8_OR_LATER) {
//Right, that is the point
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
|UIRemoteNotificationTypeSound
|UIRemoteNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
else{
//register to receive notifications
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
[application registerForRemoteNotifications];
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token=[deviceToken description];
token=[token stringByReplacingOccurrencesOfString:#">" withString:#""];
token=[token stringByReplacingOccurrencesOfString:#"<" withString:#""];
token=[token stringByReplacingOccurrencesOfString:#" " withString:#""];
if (token != nil) {
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"DEVICE_TOKEN"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
NSLog(#"token-->%#",token);
}
-(void)registerDeviceToken
{
NSUserDefaults* errDefaults = [NSUserDefaults standardUserDefaults];
NSString *regerr = #"no valid 'aps-environment' entitlement string found for application";
if ([[errDefaults objectForKey:#"ErrDesc"] isEqual: regerr] || [errDefaults objectForKey:#"DEVICE_TOKEN"] == nil) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Device token not register." message:#"Please check in member center that you have valid provisioning profile for your app." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else{
NSUserDefaults* statusvalue = [NSUserDefaults standardUserDefaults];
NSString *status = [statusvalue objectForKey:#"status"];
NSLog(#"Status->%#",status);
if ([status isEqualToString: #"SUCCESS"])
{
NSLog(#"%#",#"No need to register!!!");
}
else
{
NSString *urlString=[NSString stringWithFormat:#"%#?email=®id=%#&app_type=utnews_v1&mobile=%#",webAPIURL,[[NSUserDefaults standardUserDefaults] objectForKey:#"DEVICE_TOKEN"],[[NSUserDefaults standardUserDefaults] objectForKey:#"mobile_no"]];
NSURL *url=[NSURL URLWithString:urlString];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSLog(#"url-->%#",request.URL);
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if(error)
{
[[[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if (data.length>0)
{
NSString *responseString=[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
NSLog(#"Response string-->%#",responseString);
NSMutableDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSString *parsevalue = parsedObject[#"status"];
NSLog(#"%#",parsevalue);
NSUserDefaults* statusvalue = [NSUserDefaults standardUserDefaults];
// Store data in prefereances
[statusvalue setObject:parsevalue forKey:#"status"];
// Save to disk
[statusvalue synchronize];
// NSDictionary *jsonDict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
else
{
// [[[UIAlertView alloc] initWithTitle:#"Alert" message:#"No response from server.Please try again." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
}];
}
}
}
May be you should add [[UIApplication sharedApplication] registerForRemoteNotifications]; in if(IS_OS_8_OR_LATER) statement. Hope it help
Below code might be solved your problem from version iOS 6 and greater.
registerForRemoteNotificationTypes is Deprecated from `iOS 8.0.
#ifdef __IPHONE_8_0
if (IS_OS_EQUAL_GRETER_8) {
[[UIApplication sharedApplication] registerForRemoteNotifications];
UIUserNotificationSettings *notificationSetting=[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeSound| UIRemoteNotificationTypeBadge categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:notificationSetting];
}else{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound| UIRemoteNotificationTypeBadge)];
}
#else
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound| UIRemoteNotificationTypeBadge)];
#endif
I have integrated google plus in my ios app ,I am able to get access token.I have used authentication flow to integrate google plus.So now after getting access token how can i get user profile details like username, email id, profile pic etc?
My code to get access token is as below:
-(IBAction)btnGooglePlusClicked:(UIButton *)sender
{
IBwebView.hidden = FALSE;
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CALL_BACK_URL,GOOGLE_PLUS_SCOPE,GOOGLE_PLUS_VISIBLE_ACTIONS];
[IBwebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// [indicator startAnimating];
if ([[[request URL] host] isEqualToString:#"localhost"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
NSLog(#"verifier %#",verifier);
break;
}
}
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CLIENT_SECRET,GOOGLE_PLUS_CALL_BACK_URL];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSLog(#"verifier %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"%#", error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
SBJsonParser *jResponse = [[SBJsonParser alloc]init];
NSDictionary *tokenData = [jResponse objectWithString:response];
// WebServiceSocket *dconnection = [[WebServiceSocket alloc] init];
// dconnection.delegate = self;
NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#", [tokenData objectForKey:#"refresh_token"], self.isLogin];
// NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#",[tokenData accessToken.secret,self.isLogin];
// [dconnection fetch:1 withPostdata:pdata withGetData:#"" isSilent:NO];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Google Access TOken"
message:pdata
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
I feel the the method you are using will not help to get the profile detail.
I suggest to use the proper method which ensures the best results.
Please check this out : https://developers.google.com/+/mobile/ios/
This will surely help you to get required outcome.
I'm using NSURLConnection and NSURLRequest to do a HTTP POST of some XML data to a server.
However the server cannot find the data in the HTTP body because it has been packaged up assuming a web page is doing a form submission (parameter=form-urlencoded is getting set, presumably by default by NSURLConnection?).
This is not something I am doing explicitly, I am simply adding the body data using:
[request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];
How can I stop/override this behaviour?
I don't know the default value, but you can change it with:
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
Take a look to the documentation.
Here, I am posting XML data on web server and getting xml response using NSURLConnection. Steps are followings:
1) Post Data on server through NSURLConnection asynchronous request
NSMutableString *productDetailString =[[NSMutableString alloc] init];
[productDetailString appendString:#"<product>"];
[productDetailString appendFormat:#"<product_name>%#</product_name>",name];
[productDetailString appendString:#"<product_id>1024</product_id>"];
[productDetailString appendString:#"</product>"];
NSString *message=[[NSString alloc] initWithFormat:#"_xmlrequestPostage=%#",productDetailString];
// NSString *message=[[NSString alloc] initWithFormat:#"_xmlrequestPostage="
// "<product>\n"
// "<product_name>%#</product_name>\n"
// "<product_id>%#</product_id>\n"
// "</product>\n",name, id];
NSString *urlString = [NSString stringWithFormat:#"http://flightsflights.com.au/Mega/product.asmx/GetProductPrice"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
//set headers
NSString *contentType = [NSString stringWithFormat:#"application/x-www-form-urlencoded"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request addValue:[NSString stringWithFormat:#"%d",[message length]] forHTTPHeaderField:#"Content-Length"];
//create the body
NSMutableData *postBody = [[NSMutableData alloc]initWithData:[[NSString stringWithFormat:#"%#",message] dataUsingEncoding:NSUTF8StringEncoding]];
//post
[request setHTTPBody:postBody];
//get response
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if(connection)
{
webData=[[NSMutableData data] retain];
}
else
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Mega Australia" message:#"Problem in network." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
2) Notify delegates of NSURLConnection class
-(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
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Error" message:#"ERROR with conenction " delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(webData==nil)
{
UIAlertView *thealert=[[UIAlertView alloc] initWithTitle:#"Error" message:#"No data found." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[thealert show];
[thealert release];
}
else
{
NSString *str=[[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
str=[str stringByReplacingOccurrencesOfString:#"<" withString:#"<"];
str=[str stringByReplacingOccurrencesOfString:#">" withString:#">"];
NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
product=[[NSMutableArray alloc] init];
NSXMLParser *xmlParser=[[NSXMLParser alloc] initWithData:data];
xmlParser.delegate=self;
[xmlParser parse];
webData=nil;
[webData release];
}
}
3) Add following variables in .h file:
{
NSMutableData *webData;
NSMutableDictionary *aProduct;
NSMutableArray *product;
NSMutableString *name, *pro_id, *currentElement, *statusCode;
}
#property (retain, nonatomic) NSMutableString *name;
#property (retain, nonatomic) NSMutableString *pro_id;
#property (retain, nonatomic) NSMutableString *statusCode;
4) Synthesis name, pro_id and statusCode in .m file
5) Notify delegates for NSXMLParse class
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
currentElement=[elementName copy];
if([elementName isEqualToString:#"product"])
{
self.name=[[NSMutableString alloc] init];
self.pro_id=[[NSMutableString alloc] init];
aProduct=[[NSMutableDictionary alloc] init];
}
else if([elementName isEqualToString:#"status"])
{
self.statusCode=[[NSMutableString alloc] init];
}
}
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if([currentElement isEqualToString:#"product_name"])
{
[self.name appendString:string];
}
else if([currentElement isEqualToString:#"product_id"])
{
[self.pro_id appendString:string];
}
else if([currentElement isEqualToString:#"status"])
{
[self.statusCode appendString:string];
if(![self.statusCode isEqualToString:#"200"])
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Mega Australia" message:#"Input string is not in a correct format." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
[alert release];
return;
}
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"product"])
{
[aProduct setObject:self.name forKey:#"name"];
[aProduct setObject:self.pro_id forKey:#"id"];
[product addObject:[aProduct copy]];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
return;
}