error in uploading photo on facebook wall using graph API - iphone

I am going to work on iphone app which upload the photos on facebook wall.
I am using this code
here
- (void)rateTapped:(id)sender {
NSString *likeString;
NSString *filePath = nil;
if (_imageView.image == [UIImage imageNamed:#"angelina.jpg"]) {
filePath = [[NSBundle mainBundle] pathForResource:#"angelina" ofType:#"jpg"];
likeString = #"babe";
} else if (_imageView.image == [UIImage imageNamed:#"depp.jpg"]) {
filePath = [[NSBundle mainBundle] pathForResource:#"depp" ofType:#"jpg"];
likeString = #"dude";
} else if (_imageView.image == [UIImage imageNamed:#"maltese.jpg"]) {
filePath = [[NSBundle mainBundle] pathForResource:#"maltese" ofType:#"jpg"];
likeString = #"puppy";
}
if (filePath == nil) return;
NSString *adjectiveString;
if (_segControl.selectedSegmentIndex == 0) {
adjectiveString = #"cute";
} else {
adjectiveString = #"ugly";
}
NSString *message = [NSString stringWithFormat:#"I think this is a %# %#!", adjectiveString, likeString];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me/photos"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addFile:filePath forKey:#"file"];
//[request setFile:filePath withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"photo"];
[request setPostValue:message forKey:#"message"];
[request setPostValue:_accessToken forKey:#"access_token"];
[request setDidFinishSelector:#selector(sendToPhotosFinished:)];
[request setDelegate:self];
[request startAsynchronous];
}
here i got Photo id is: (null)
- (void)sendToPhotosFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *photoId = [responseJSON objectForKey:#"id"];
NSLog(#"Photo id is: %#", photoId);
NSString *urlString = [NSString stringWithFormat:#"https://graph.facebook.com/%#?access_token=%#", photoId, [_accessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *newRequest = [ASIHTTPRequest requestWithURL:url];
[newRequest setDidFinishSelector:#selector(getFacebookPhotoFinished:)];
[newRequest setDelegate:self];
[newRequest startAsynchronous];
}
- (void)getFacebookProfileFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSLog(#"Got Facebook Profile: %#", responseString);
NSString *likesString;
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSArray *interestedIn = [responseJSON objectForKey:#"interested_in"];
if (interestedIn != nil) {
NSString *firstInterest = [interestedIn objectAtIndex:0];
if ([firstInterest compare:#"male"] == 0) {
[_imageView setImage:[UIImage imageNamed:#"depp.jpg"]];
likesString = #"dudes";
} else if ([firstInterest compare:#"female"] == 0) {
[_imageView setImage:[UIImage imageNamed:#"angelina.jpg"]];
likesString = #"babes";
}
} else {
[_imageView setImage:[UIImage imageNamed:#"maltese.jpg"]];
likesString = #"puppies";
}
NSString *username;
NSString *firstName = [responseJSON objectForKey:#"first_name"];
NSString *lastName = [responseJSON objectForKey:#"last_name"];
if (firstName && lastName) {
username = [NSString stringWithFormat:#"%# %#", firstName, lastName];
} else {
username = #"mysterious user";
}
_textView.text = [NSString stringWithFormat:#"Hi %#! I noticed you like %#, so tell me if you think this pic is hot or not!",
username, likesString];
[self refresh];
}
But here am suffered from following error
here in Console i got an error : Got Facebook Photo: {"error":{"message":"(#803) Some of the aliases you requested do not exist: (null)","type":"OAuthException"}}
I tried this by changing various App ID but my problem doesn't solve.
Anyone help me to achieve this.........
Thanks In advance...

You try like this,
NSData *imagedata = UIImageJPEGRepresentation(urPhoto, 10);
[newRequest setPostValue:imagedata forKey:#"data"];
or add image like this,
[newRequest setPostValue:link forKey:#"data"];

Related

DocuSign error downloading document

I'm trying to implement this example link of a DocuSign service that download an envelope document, but when the execution arrive to this line in step 3:
NSMutableString *jsonResponse = [[NSMutableString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
jsonResponse is nil and when I open the document, it has a lot of strange characters and I can't read it.
My code for downloadind is the following:
NSString *url = #"https://demo.docusign.net/restapi/v2/accounts/373577/envelopes/08016140-e4dc-4697-8146-f8ce801abf92/documents/1";
NSMutableURLRequest *documentsRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[documentsRequest setHTTPMethod:#"GET"];
[documentsRequest setURL:[NSURL URLWithString:url]];
[documentsRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[documentsRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
NSError *error1 = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:documentsRequest returningResponse:&responseCode error:&error1];
NSMutableString *jsonResponse = [[NSMutableString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
if([responseCode statusCode] != 200){
NSLog(#"Error sending %# request to %#\nHTTP status code = %i", [documentsRequest HTTPMethod], url, [responseCode statusCode]);
NSLog( #"Response = %#", jsonResponse );
return;
}
// download the document to the same directory as this app
NSString *appDirectory = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
NSMutableString *filePath = [NSMutableString stringWithFormat:#"%#/%#", appDirectory, #"eee"];
[oResponseData writeToFile:filePath atomically:YES];
NSLog(#"Envelope document - %# - has been downloaded to %#\n", #"eee", filePath);
If no data is coming back from
NSMutableString *jsonResponse = [[NSMutableString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
then that means oResponseData is most likely nil which means the URL is not being constructed correctly for each envelope document. Are you doing step 2 in the sample that you linked to, where it first retrieves the envelopeDocuments information about the envelope, then it dynamically builds each unique document uri in preparation of downloading each one.
Instead of hardcoding your URL you should dynamically retrieve the envelopeDocuments data, then build each document uri dynamically then your response data will not be nil. Here's the full working sample:
- (void)getDocumentInfoAndDownloadDocuments
{
// Enter your info:
NSString *email = #"<#email#>";
NSString *password = #"<#password#>";
NSString *integratorKey = #"<#integratorKey#>";
// need to copy a valid envelopeId from your account
NSString *envelopeId = #"<#envelopeId#>";
///////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Login (retrieves accountId and baseUrl)
///////////////////////////////////////////////////////////////////////////////////////
NSString *loginURL = #"https://demo.docusign.net/restapi/v2/login_information";
NSMutableURLRequest *loginRequest = [[NSMutableURLRequest alloc] init];
[loginRequest setHTTPMethod:#"GET"];
[loginRequest setURL:[NSURL URLWithString:loginURL]];
// set JSON formatted X-DocuSign-Authentication header (XML also accepted)
NSDictionary *authenticationHeader = #{#"Username": email, #"Password" : password, #"IntegratorKey" : integratorKey};
// jsonStringFromObject() function defined further below...
[loginRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
// also set the Content-Type header (other accepted type is application/xml)
[loginRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:loginRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *loginResponse, NSData *loginData, NSError *loginError) {
if (loginError) { // succesful GET returns status 200
NSLog(#"Error sending request %#. Got Response %# Error is: %#", loginRequest, loginResponse, loginError);
return;
}
// we use NSJSONSerialization to parse the JSON formatted response
NSError *jsonError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:loginData options:kNilOptions error:&jsonError];
NSArray *loginArray = responseDictionary[#"loginAccounts"];
// parse the accountId and baseUrl from the response (other data included)
NSString *accountId = loginArray[0][#"accountId"];
NSString *baseUrl = loginArray[0][#"baseUrl"];
//--- display results
NSLog(#"\naccountId = %#\nbaseUrl = %#\n", accountId, baseUrl);
///////////////////////////////////////////////////////////////////////////////////////
// STEP 2 - Get Document Info for specified envelope
///////////////////////////////////////////////////////////////////////////////////////
// append /envelopes/{envelopeId}/documents URI to baseUrl and use as endpoint for next request
NSString *documentsURL = [NSMutableString stringWithFormat:#"%#/envelopes/%#/documents", baseUrl, envelopeId];
NSMutableURLRequest *documentsRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:documentsURL]];
[documentsRequest setHTTPMethod:#"GET"];
[documentsRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[documentsRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
[NSURLConnection sendAsynchronousRequest:documentsRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *documentsResponse, NSData *documentsData, NSError *documentsError) {
NSError *documentsJSONError = nil;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:documentsData options:kNilOptions error:&documentsJSONError];
if (documentsError){
NSLog(#"Error sending request: %#. Got response: %#", documentsRequest, documentsResponse);
NSLog( #"Response = %#", documentsResponse );
return;
}
NSLog( #"Documents info for envelope is:\n%#", jsonResponse);
NSError *jsonError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:documentsData options:kNilOptions error:&jsonError];
// grab documents info for the next step...
NSArray *documentsArray = responseDictionary[#"envelopeDocuments"];
///////////////////////////////////////////////////////////////////////////////////////
// STEP 3 - Download each envelope document
///////////////////////////////////////////////////////////////////////////////////////
NSMutableString *docUri;
NSMutableString *docName;
NSMutableString *docURL;
// loop through each document uri and download each doc (including the envelope's certificate)
for (int i = 0; i < [documentsArray count]; i++)
{
docUri = [documentsArray[i] objectForKey:#"uri"];
docName = [documentsArray[i] objectForKey:#"name"];
docURL = [NSMutableString stringWithFormat: #"%#/%#", baseUrl, docUri];
[documentsRequest setHTTPMethod:#"GET"];
[documentsRequest setURL:[NSURL URLWithString:docURL]];
[documentsRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[documentsRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:documentsRequest returningResponse:&responseCode error:&error];
NSMutableString *jsonResponse = [[NSMutableString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
if([responseCode statusCode] != 200){
NSLog(#"Error sending %# request to %#\nHTTP status code = %i", [documentsRequest HTTPMethod], docURL, [responseCode statusCode]);
NSLog( #"Response = %#", jsonResponse );
return;
}
// download the document to the same directory as this app
NSString *appDirectory = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
NSMutableString *filePath = [NSMutableString stringWithFormat:#"%#/%#", appDirectory, docName];
[oResponseData writeToFile:filePath atomically:YES];
NSLog(#"Envelope document - %# - has been downloaded to %#\n", docName, filePath);
} // end for
}];
}];
}
- (NSString *)jsonStringFromObject:(id)object {
NSString *string = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:object options:0 error:nil] encoding:NSUTF8StringEncoding];
return string;
}

Xcode Parse Json Data

My code below was working, before, but suddenly it stopped working. Could anyone tell me what I'm doing wrong?
Output of NSLog():
2013-05-14 16:06:35.475 Run.PH[1502:19a03] background = (null)
2013-05-14 16:06:35.476 Run.PH[1502:19a03] logo = (null)
2013-05-14 16:06:35.476 Run.PH[1502:19a03] json = (null)
2013-05-14 16:06:35.476 Run.PH[1502:19a03] welcome = (null)
Codes:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *urlString = [NSString stringWithFormat:#"http://run.ph/json/test_json_dyna.jsp"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data != nil)
{
NSError *error;
_json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
_welcomeMessage.text = [[_json objectForKey:#"welcome"] objectForKey:#"message"];
NSString *background = [[_json objectForKey:#"welcome"] objectForKey:#"background"];
NSString *logo = [[_json objectForKey:#"welcome"] objectForKey:#"logo"];
NSLog(#"background = %#", background);
NSLog(#"logo = %#", logo);
NSLog(#"json = %#", _json);
NSLog(#"welcome = %#", _welcomeMessage.text);
NSURL *urlBackground = [NSURL URLWithString:background];
NSData *dataBackground = [NSData dataWithContentsOfURL:urlBackground];
[_background setImage:[UIImage imageWithData:dataBackground]];
NSURL *urlLogo = [NSURL URLWithString:logo];
NSData *dataLogo = [NSData dataWithContentsOfURL:urlLogo];
[_logo setImage:[UIImage imageWithData:dataLogo]];
}
else
{
NSLog(#"Error!");
}
[self.view reloadInputViews];
}
Just NSLog your URL response you will get wats wrong with your json.
Try this
NSString *respo = [NSString stringWithContentsOfURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
NSLog(#"Response - %#",respo);
It has return "\r" and newline character "\n" with your response.
Check this
EDIT
Now your URL is working fine, problem was with your web service end.

Prevent iCloud Backup

I make and app that the people download content and they can access it offline, it likes a catalogue. But Apple reject it because it baking up in iCloud i I'm doing the following but it seems not working.
Funciones.m
+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL {
const char* filePath = [[URL path] fileSystemRepresentation];
const char* attrName = "com.apple.MobileBackup";
u_int8_t attrValue = 1;
int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
return result == 0;
}
Update.m
- (void)updateImg:(NSString *)tipo {
//tomamos el ultimo update
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSTimeInterval time = [defaults doubleForKey:#"lastUpdate"];
NSLog(#"%f", time);
CatalogoAppDelegate *app = [[UIApplication sharedApplication] delegate];
NSString *post = [NSString stringWithFormat:#"lastUpdate=%f", time];
NSData *postData = [post dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:NO];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *url = [NSString stringWithFormat:#"%#iPhone/update%#Img.php", app.serverUrl, tipo];
[urlRequest setURL:[NSURL URLWithString:url]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if(urlData) {
NSString *aStr = [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]autorelease];
//NSLog(#"%#: %#", tipo, aStr);
NSArray *temp = [aStr componentsSeparatedByString:#";"];
//Direccionl Local de la APP
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
for (int i=0; i<[temp count]; i++) {
NSString *tempImg = [NSString stringWithFormat:#"%#", [temp objectAtIndex:i]];
//NSLog(#"%#", tempImg);
//pedimos cada url
NSURL *tempURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#images/%#/%#", app.serverUrl, tipo, tempImg]];
//[Funciones addSkipBackupAttributeToItemAtURL:tempURL];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:tempURL]];
NSLog(#"%#images/%#/%#", app.serverUrl, tipo, tempImg);
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#", docDir, tempImg];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
NSURL *backUrl = [NSURL fileURLWithPath:pngFilePath];
[Funciones addSkipBackupAttributeToItemAtURL:backUrl];
}
}
[self performSelectorInBackground:#selector(finUpdate) withObject:nil];
}
Any idea what I am doing wrong?
Thanks
setxattr provides a result indicating success or an error, and Apple's addSkipBackupAttributeToItemAtURL: method checks for an error and passes this information back to your code. Your code simply ignores it. Start by determining if it's returning an error or not.
Maybe it's because your app is compatible with iOS 5.0.
Do not backup variable is only available since 5.1. Details here http://developer.apple.com/library/ios/#qa/qa1719/_index.html#//apple_ref/doc/uid/DTS40011342

How to know if data is present in url are not

I have written code like this but I can't understand how to find if the data is present or not in the URL. Can anyone help me in solving this problem?
Note: This code terminates when the loop is entering the second condition. That is where it's terminating.
-(void)getdetails
{
NSLog(#"in get details");
NSURL *jsonurl=[NSURL URLWithString:#"http://www.myappdemo.com/checkout/services/getonlineusers.php"];
NSMutableURLRequest *request=[[[NSMutableURLRequest alloc]init ]autorelease];
[request setURL:jsonurl];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSURLResponse *response;
NSData *serverReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *replyString = [[NSString alloc] initWithBytes:[serverReply bytes] length:[serverReply length] encoding: NSASCIIStringEncoding];
if([replyString isEqualToString:#"Invalid."]){ // i have not set the php code to output "invalid" so this will not work for now ...
NSLog(#"%#",replyString);
}
else {
NSMutableArray *tempArray =[replyString JSONValue];
int count=0;
self.temparray=tempArray;
for(int i=0;i<[tempArray count];i++)
{
///////Here in this loop when it is entering it is terminating /////////
NSDictionary *dict=[tempArray objectAtIndex:i];
NSLog(#"DICT is %#",dict);
NSString *string=[dict objectForKey:#"profilepic"];
NSURL *finalURL = [NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSLog(#"encoding string is %#",finalURL);
NSURL *url=[NSURL URLWithString:string];
NSString *source = [NSString stringWithContentsOfURL:finalURL encoding:NSUTF8StringEncoding error:nil];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:url];
NSLog(#"url is %#",url);
NSData *data=[NSData dataWithContentsOfURL:url];
if(!(data==nil))
{
NSLog(#"data is there");
UIImage *image=[[UIImage alloc]initWithData:data];
[self.array addObject:image];
[image release];
}
else {
/*
NSLog(#"if data is null condition block");
UIImage *image=[[UIImage alloc]init];
[self.array addObject:image];
[image release];
*/
}
count=count+1;
NSLog(#"count is %d",count);
}
}
[replyString release];
}
Where does the app terminate and what is the exception? Have you stepped through to see what the array object looks like during each iteration? Is it failing at NSData initWithContentsOfURL? Why don't you issue that as a separate synchronous request and test to see if you got a response?
Regarding your first (and any subsequent) synchronous request, it would probably be good to add a check to ensure you received a valid response (sorry for the formatting, the code tag isn't playing nicely at the moment)
if (response!=nil) {if([response isKindOfClass:[NSHTTPURLResponse class]]) {
// you have a valid response }}

Marking items as read / unread in iphone google reader app

I am developing an app using data from google reader's API and using GData for login.
I want to be able to mark a post inside a table cell as read / unread, but am finding the fact that this is all mainly undocumented hard to work out a solution, any ideas / links?
Here is the code for the mark read button:
//Get the token
NSString *tokenString = [NSString stringWithFormat:#"https://www.google.com/reader/api/0/token"];
NSURL *tokenURL = [NSURL URLWithString:tokenString];
NSMutableURLRequest *tokenRequest = [NSMutableURLRequest requestWithURL:tokenURL];
NSString *tokenStringResult;
NSArray *listItems;
NSError *tokenError = nil;
NSURLResponse *tokenResponse = nil;
NSData *tokenData = [NSURLConnection sendSynchronousRequest:tokenRequest
returningResponse:&tokenResponse
error:&tokenError];
if (tokenData)
{
tokenStringResult = [[NSString alloc] initWithData:tokenData encoding:NSUTF8StringEncoding];
listItems = [tokenStringResult componentsSeparatedByString:#"/"];
}
else
{
NSLog(#"tokenError = %#", tokenError);
}
// Mark it as read
NSString *readerURLString = [NSString stringWithFormat:#"http://www.google.com/reader/api/0/edit-tag?a=user/-/state/com.google/read&async=true&s=feed/%#&i=%#&T=%#", siteLink, postID, [listItems lastObject]];
NSURL *readerURL = [NSURL URLWithString:readerURLString];
NSMutableURLRequest *readerRequest = [NSMutableURLRequest requestWithURL:readerURL];
[mAuth authorizeRequest:readerRequest];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:readerRequest
returningResponse:&response
error:&error];
if (data)
{
NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) response;
assert( [httpResponse isKindOfClass:[NSHTTPURLResponse class]] );
NSLog(#"response.allHeaderFields = %#", [httpResponse allHeaderFields]);
NSLog(#"response.statusCode = %i", [httpResponse statusCode]);
}
the log from this is:
response.statusCode = {
"Cache-Control" = "private, max-age=0";
"Content-Length" = 1334;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Fri, 21 Jan 2011 03:49:07 GMT";
Expires = "Fri, 21 Jan 2011 03:49:07 GMT";
Server = GSE;
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-Reader-Google-Version" = "527-000";
"X-Reader-User" = 01940378872835844713;
"X-Xss-Protection" = "1; mode=block";
}
response.statusCode = 400
So through alot of trial and error I've got it working.
EDIT - Added Auth code
NSString *GOOGLE_CLIENT_AUTH_URL = #"https://www.google.com/accounts/ClientLogin?client=SomeName";
NSString *gSourceString = #"SomeName";
NSMutableURLRequest *httpReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:GOOGLE_CLIENT_AUTH_URL]];
[httpReq setTimeoutInterval:30.0];
[httpReq setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[httpReq setHTTPMethod:#"POST"];
[httpReq addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *requestBody = [[NSString alloc] initWithFormat:#"Email=%#&Passwd=%#&service=reader&accountType=HOSTED_OR_GOOGLE&source=%#", userString, passwordString, [NSString stringWithFormat:#"%#%d", gSourceString]];
[httpReq setHTTPBody:[requestBody dataUsingEncoding:NSASCIIStringEncoding]];
[requestBody release];
NSHTTPURLResponse *response = nil;
NSData *data = nil;
NSString *responseStr = nil;
NSArray *responseLines = nil;
int responseStatus = 0;
data = [NSURLConnection sendSynchronousRequest:httpReq returningResponse:&response error:&error];
[httpReq release];
if ([data length] > 0)
{
responseStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
responseStatus = [response statusCode];
if (responseStatus == 200 )
{
authOK = TRUE;
NSLog(#"Successfully authenticated with Google.");
NSArray *authLines = nil;
authLines = [responseStr componentsSeparatedByString:#"\n"];
int j;
for (j =0; j < [authLines count]; j++ )
{
if ([[authLines objectAtIndex:j] rangeOfString:#"Auth="].length != 0) {
NSMutableString *teststring = [NSMutableString stringWithString:[authLines objectAtIndex:j]];
[teststring replaceCharactersInRange:NSMakeRange(0,4) withString:#"auth"];
authString = teststring;
}
}
}
}
NSString *auth = [[NSString alloc] initWithString: [NSString stringWithFormat:#"GoogleLogin %#", authString]];
NSDictionary *createHeader = [[NSDictionary dictionaryWithObjectsAndKeys:#"www.google.com", #"Host", #"EditApp", #"User-Agent", #"gzip, deflate", #"Accept-Encoding", auth, #"Authorization", nil]retain];
[auth release];
NSURL *url =[NSURL URLWithString:#"http://www.google.com/reader/api/0/token?client=EditApp"];
NSData *recieveData;
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:url];
[urlRequest setHTTPMethod:#"GET"];
[urlRequest setAllHTTPHeaderFields:createHeader];
NSURLResponse *response;
NSError *error;
recieveData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
// Get token
NSString *pretokenString = [[NSString alloc] initWithData:recieveData encoding:NSASCIIStringEncoding];
tokenString = [pretokenString substringWithRange:NSMakeRange(2, [pretokenString length]-2)];
[pretokenString release];
[urlRequest release];
NSMutableURLRequest *thttpReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.google.com/reader/api/0/edit-tag?"]];
[thttpReq setTimeoutInterval:30.0];
[thttpReq setHTTPMethod:#"POST"];
NSString *authHeader = [NSString stringWithFormat:#"GoogleLogin %#", authString];
[thttpReq addValue:authHeader forHTTPHeaderField:#"Authorization"];
[thttpReq addValue:#"Content-Type" forHTTPHeaderField:#"application/x-www-form-urlencoded"];
// siteLink is the url of the feed
// googlePostID is the id from the XML output: tag:google.com,2005:reader/item/e3345c69e174bdec
NSString *trequestBody = [[NSString alloc] initWithFormat:#"a=user/-/state/com.google/read&ac=edit-tags&s=feed/%#&i=%#&T=%#", siteLink, googlePostID, tokenString];
[thttpReq setHTTPBody:[trequestBody dataUsingEncoding:NSASCIIStringEncoding]];
NSURLConnection *con = [[NSURLConnection alloc]
initWithRequest:thttpReq
delegate:self
startImmediately:NO];
[con scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
[con start];
If you are familiar with php I wrote a tutorial on using the google readi api recently.
http://mobile.tutsplus.com/tutorials/mobile-web-apps/building-a-mobile-web-application-with-the-google-reader-api/
One thing I notice is that in this string
http://www.google.com/reader/api/0/edit-tag/a=user/-/state/com.google/read&async=true&s=feed/%#&i=%#
Your not including the "edit" token the url should look like this. and you need the ? after edit-tag.
http://www.google.com/reader/api/0/edit-tag?a=user/-/state/com.google/read&async=true&s=feed/%#&i=%#&T=%#
You can get the "edit" token from this link once you have the user logged in, https://www.google.com/reader/api/0/token
Sorry can't help with objective-c stuff.