NSData dataWithContentsOfURL returns nil - nsdata

I am trying to fetch a XML file from a URL and store it locally, yet I find the [NSData dataWithContentsOfURL xxxx] returns nil to me.
The error message reads: operation couldn’t be completed. (Cocoa error 256.)
Could you help to review my code and point to me the problem:
NSError* err = nil;
NSString* urlString = #"http://www.w3school.com.cn/example/xmle/note.xml";
NSURL* xmlUrl = [NSURL URLWithString:urlString];
NSData* xmlData = [NSData dataWithContentsOfURL:xmlUrl options: NSDataReadingUncached error: &err];

Related

How to translate the object c into rubymotion to fetch facebook user’s information

I tried to translate part of the objective-c but I still stuck at part of them
any idea ? Thanks so much
objective c version
if ([FBSDKAccessToken currentAccessToken]) {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"picture",#"fields",nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me"
parameters:params
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
UIImage * downloadedImage = [UIImage imageWithData:pictureData];
dispatch_async(dispatch_get_main_queue(), ^{
self.profilePictureImageView.image = downloadedImage;
});
}];
}
ruby motion version
if (FBSDKAccessToken.currentAccessToken) {
request = FBSDKGraphRequest.alloc.initWithGraphPath("me", parameters:nil, HTTPMethod: "GET")
}
Finally, I came up with the corresponding code in rubymotion
Please correct me directly if anything wrong, it works for me now
part of original objective-c
if ([FBSDKAccessToken currentAccessToken]) {
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me"
parameters:params
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
}];
}
convert version by ruby_motion_query
def loginButton(loginButton, didCompleteWithResult: result, error: error)
puts result
puts error
if not error
request = FBSDKGraphRequest.alloc.initWithGraphPath("me", parameters:nil, HTTPMethod: "GET")
request.startWithCompletionHandler( lambda{ |connection, user, error|
#DO_ANYTHING_YOU_WANT_FATE_LOGINING_SUCESSFULLY
rmq(#fb_login_button).animate { |btn| btn.move(b: 400) }
#name_label = rmq.append(UILabel, :label_name).get
#name_label.text = "#{user['first_name']} #{user['last_name']}"
rmq(#name_label).animations.fade_in
})
end
end
def loginButtonDidLogOut(loginButton)
#DO_ANYTHING_YOU_WANT_HERE
end

Can not get friends name, pic_quare from Facebook in iOS?

When I am Fetching name and pic_square from my friend list the it shows the following error.
Error: The operation couldn’t be completed. (com.facebook.sdk error 5.)
FBSDKLog: Error: HTTP status code: 400
FBSDKLog: Response <#1386> <Error>:
The operation couldn’t be completed. (com.facebook.sdk error 5.)
{
"com.facebook.sdk:ErrorSessionKey" = "<FBSession: 0x146f1600, state: FBSessionStateOpen, loginHandler: 0x146cca50, appID: 293072694193895, urlSchemeSuffix: , tokenCachingStrategy:<FBSessionTokenCachingStrategy: 0x1468b170>, expirationDate: 2014-07-17 07:47:12 +0000, refreshDate: 2014-05-18 11:14:42 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(\n status,\n permission\n)>";
"com.facebook.sdk:HTTPStatusCode" = 400;
"com.facebook.sdk:ParsedJSONResponseKey" = (
{
body = {
error = {
code = 606;
message = "(#606) The global ID 100003190599973 is not allowed. Please use the application specific ID instead.";
type = OAuthException;
};
};
code = 400;
}
);
}
here I used the code for retrieving the the required information
NSString *query = [NSString stringWithFormat:#"select name, pic_square from user where uid = %#", curId];
NSDictionary *queryParam = [NSDictionary dictionaryWithObjectsAndKeys:query, #"q", nil];
// Make the API request that uses FQL
[FBRequestConnection startWithGraphPath:#"/fql" parameters:queryParam HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (error)
NSLog(#"Error: %#", [error localizedDescription]);
else
{
[namePicArray addObject:result[#"data"]];
}
}];
Thanks in advance.

Uploading multiple binary items as part of a batch call on iOS

I'm trying to make post with more than a photo in Fb using batch request but I keep getting timeout errors from Fb server...
This is my code ..
UIImage *imgFile1 = [UIImage imageNamed:#"iTGps.png"];
NSData *imageData = UIImageJPEGRepresentation(imgFile1, 0.5);
NSString *jsP1 = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"me/photos\",\"body\":\"message=My cat photo\",\"attached_files\":\"%#\"}",imageData];
NSString *jsonRequestsArray = [NSString stringWithFormat:#"[%#,%#,%#]",jsP1,jsP1,jsP1];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:jsonRequestsArray forKey:#"batch"];
FBRequestConnection *connect = [[FBRequestConnection alloc] initWithTimeout:60];
// do Fb request
FBRequest *request = [FBRequest requestWithGraphPath:#"me/photos"
parameters:params
HTTPMethod:#"POST"];
// add connection
[connect addRequest:request
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
NSLog(#"Result:%#,%#",result,error);
}];
[connect start];
Where am I doing wrong??
Error code is very long so i cut the middle part (i think is the binary images)
2013-04-28 20:03:32.435 trueGps[1887:1a603] Result:(null),Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x14454010 {com.facebook.sdk:ErrorInnerErrorKey=Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x14492d40 {NSErrorFailingURLStringKey=https://graph.facebook.com/me/photos?sdk=ios&batch=%5B%7B%20%22method%22%3A%20%22POST%22%2C%20%22relative_url%22%3A%20%22me%2Fphotos%22%2C%22body%22%3A%22message%3DMy%20cat%20photo%22%2C%22attached_files ....
NSLocalizedDescription=The request timed out., NSUnderlyingError=0x2a90f620 "The request timed out."}, com.facebook.sdk:HTTPStatusCode=200}
i solve the problem .. but still have more post with only a photo in every one..
NSString *rel_url = [NSString stringWithFormat:#"%#/photos",nomeAlbum];
NSString *jsP1 = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"%#\", \"body\": \"message=My_cat_photo\", \"attached_files\": \"file1\" }",rel_url];
NSString *jsonRequestsArray = [NSString stringWithFormat:#"[%#]",jsP1];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:jsonRequestsArray forKey:#"batch"];
[params setObject:imgFile1 forKey:#"file1"];
[FBRequestConnection startWithGraphPath:rel_url
parameters:postParams
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
}];

ASIFormDataRequest post type

I need to send RestFul Web Service Request with post type ,post data format is like as below {"Request":"parameters".... }and binary data with same request.Is it possible with ios if possible means explain please?
I don't recommend using the ASIHttpRequest library anymore because it's not getting any updates from the developer , as to how to create a post http request here's an example
NSString *url = #"your webservice base url";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSString *param2 = ...//
NSData *binaryData = .... //initilize the binary data you want to send
NSString *bodyString = [NSString stringWithFormat:#"param1=%#&param2=%#",binartData,param2];
[request setValue:[NSString stringWithFormat:#"%d", [bodyString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[bodyString dataUsingEncoding:NSASCIIStringEncoding]];//or set the type of encoding agreed with your webservice
NSURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString;
if ( responseData && !error){
responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
}

Cannot access web service in iOS

I want to connect with a web service from my iOS app. Previously my URL was http://<domain name>/mobilews/mobilews.asmx. Recently I changed to http://<domain name>/mobilewstest/mobilews.asmx
I have put my URL in info plist file. But after I changed this into new URL I cannot login to that.
NSString *urlString = [NSString stringWithFormat:#"%#%#",serverURL,[queryString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSHTTPURLResponse *response ;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
int statusCode = [((NSHTTPURLResponse *)response) statusCode];`
Here returnData become nill and statusCode is 0. But this urlString is successfully logged in to the web service when it gives in the browser.
NSURL *url = [NSURL URLWithString:#"YOUR URL HERE"];
NSError *connectionError = nil;
NSData *inData = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&connectionError];
NSInteger code = [connectionError code];
if (code != 0)
{
NSString *locDesc = [NSString stringWithString:[connectionError localizedDescription]];
NSString *locFail = [NSString stringWithString:[connectionError localizedFailureReason]];
NSLog(#"Error: %d %# %#", code, locDesc, locFail);
}
else if ([inData length] == 0)
{
NSLog(#"No data");
}
else{
NSData *resultData = [NSData dataWithContentsOfURL:url];
NSString *responseString = [[NSString alloc]initWithData:resultData encoding:NSUTF8StringEncoding];
}
I see you send a syncronous request... try this its more an easy approach.