issue with getting data from url - ios

Here is the code I wrote
NSString *str = [NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=CAADbwxRRgq8BANULcGGn3d4NPZB4LlP3tCL9YjYH3Nd0fD2XvgjG0qTECEmOsFhNhcu4NCdgYzQK3lYaATiedLRP4ZAIRgf8FBtDBYd22z5BrMabHlex12nZAbm8UfJTrPVRw5rjN8abi9"];
NSURL* url = [NSURL URLWithString:[str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError* error = nil;
NSData* data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
NSLog(#"Data has loaded successfully.");
}
I got the error
Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be
completed. (Cocoa error 256.)" UserInfo=0x218446a0
{NSURL=https://graph.facebook.com/me?access_token=CAADbwxRRgq8BANULcGGn3d4NPZB4LlP3tCL9YjYH3Nd0fD2XvgjG0qTECEmOsFhNhcu4NCdgYzQK3lYaATiedLRP4ZAIRgf8FBtDBYd22z5BrMabHlex12nZAbm8UfJTrPVRw5rjN8abi9ZBoVD1DYVZCo8hcZC0n2CnMyk3ryeCQntRpdZCc2e}

Try:
NSString *str = [NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=CAADbwxRRgq8BANULcGGn3d4NPZB4LlP3tCL9YjYH3Nd0fD2XvgjG0qTECEmOsFhNhcu4NCdgYzQK3lYaATiedLRP4ZAIRgf8FBtDBYd22z5BrMabHlex12nZAbm8UfJTrPVRw5rjN8abi9"];
NSURL* url = [NSURL URLWithString:[str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30] returningResponse:nil error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
NSLog(#"Data has loaded successfully.");
}
Albeit, I have no idea why your other request fails. Error code 256 isn't very descriptive.

Here is a nice explanation of why NSCocoaErrorDomain occurs.
NSData dataWithContentsOfURL: not returning data for URL that shows in browser
Read it and see if any of the suggestions in that answer might be useful to you.

Related

Downloading XML file from URL returning NIL in NSData

I am trying to download an XML file from this URL www.overpass-api.de/api/xapi?[maxspeed=][bbox=5.6283473,50.5348043,5.6285261,50.534884]
but it returns nil to NSData. My code is:
NSURL *url = [NSURL URLWithString:#"www.overpass-api.de/api/xapi?*[maxspeed=*][bbox=5.6283473,50.5348043,5.6285261,50.534884]"];
NSError *error;
NSData *urlData = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
NSLog(#"Data has loaded successfully.");
}
The error says "The file “xapi” couldn’t be opened because there is no such file."
Please help how can I download the XML returned from the URL and parse it?
Got it working! Just added http:// to the beginning of the link and it returns proper data. Wow!

downloading video from youtube objective c

I'm trying to download video from youtube but getting error.
Error mention in code
my code
-(void)downloadVideo{
LBYouTubeExtractor *extractor = [[LBYouTubeExtractor alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:(#"https://www.youtube.com/watch?v=%#"), videoIdToDownload ]] quality:LBYouTubeVideoQualityLarge];
[extractor extractVideoURLWithCompletionBlock:^(NSURL *videoURL, NSError *error) {
if(!error) {
NSLog(#"Did extract video URL using completion block: %#", videoURL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError* error = nil;
NSData* data1 = [NSData dataWithContentsOfURL:videoURL options:NSDataReadingUncached error:&error]; //data1 is nill
if (error) { //Error Domain=NSCocoaErrorDomain Code=256 "The file “3gpp;+codecs="mp4v.20.3,+mp4a.40.2"&fallback_host=tc.v8.cache4.googlevideo.com&itag=36” couldn’t be opened."
NSLog(#"error=%#", error);
}else{
NSString *filename = [NSString stringWithFormat:(#"video_%#.mp4"), videoIdToDownload ];
[data1 writeToFile:[dirPath stringByAppendingPathComponent:filename] atomically:YES];
NSLog(#"File %# successfully saved", filename);
}
});
} else {
NSLog(#"Failed extracting video URL using block due to error:%#", error);
}
}];
}
using this lib
https://github.com/larcus94/LBYouTubeView
If anyone now solution please help me.
Thanks

error 401 when i request to get all contacts using GDATA

i am using Gdata and already suceessfully login gmail and call below method
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth{
if (error != nil) {
}
else{
// i got successful login here
self.auth=auth;
}
}
in above method i got Authentifacation token and etc.
Now
NSString *urlStr = #"https://www.google.com/m8/feeds/contacts/default/full";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[self.auth authorizeRequest:request
completionHandler:^(NSError *error) {
NSString *output = nil;
if (error) {
output = [error description];
} else {
// Synchronous fetches like this are a really bad idea in Cocoa applications
//
// For a very easy async alternative, we could use GTMHTTPFetcher
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (data) {
// API fetch succeeded
output = [[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding] autorelease];
} else {
// fetch failed
output = [error description];
}
}
}];
but i got error 401
please helpful me

How to parse JSONP in Objective-C?

I am retrieving JSON information for an API and it says on the API that it is in JSON but I noticed it is in JSONP or "json with padding" as some call it. I tired to look everywhere to find how to parse this but no luck. The information I am trying to receive is this:
({"book":[{"book_name":"James","book_nr":"59","chapter_nr":"3","chapter":
{"16":{"verse_nr":"16","verse":"For where envying and strife is, there is confusion and
every evil work."}}}],"direction":"LTR","type":"verse"});
The link to the data is https://getbible.net/json?p=James3:16, so you can look at it directly.
This is the code I am using to try to retrieve the JSON Data and parse it into a NSMutableDictionary.
-(void)fetchJson {
NSString *currentURL = [NSString stringWithFormat:#"https://getbible.net/json?p=James"];
NSURL *url = [NSURL URLWithString:currentURL];
NSData *data = [[NSData alloc]initWithContentsOfURL:url];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
NSMutableData *receivedData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
[receivedData setLength:0];
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:url MIMEType:#".json" expectedContentLength:-1 textEncodingName:nil];
expectedTotalSize = [response expectedContentLength];
if ([data length] !=0) {
NSLog(#"appendingData");
[receivedData appendData:data];
if(connection){
NSLog(#"Succeeded! Received %lu bytes of data",(unsigned long)[receivedData length]);
}
NSError *error;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if(jsonResponse){
NSArray *responseArr = [jsonResponse mutableCopy];
NSLog(#"%lu",(unsigned long)[responseArr count]);
}else if (!jsonResponse){
//do internet connection error response
}
}
}
The results I am getting back from putting a breakpoint in the code is:
jsonResponse returns NULL
NSError NSCocoaErrorDomain code - 3840
but my NSData *data is returning 15640 bytes.
My console is displaying this from the NSLogs I used for debugging:
2014-04-20 01:27:31.877 appendingData
2014-04-20 01:27:31.879 Succeeded! Received 15640 bytes of data
I am receiving the data correctly but I am not parsing it correctly I know the error is because the JSON is in JSONP format. If anyone could please help with this I would appreciate it so much. I have tired to give as much detail on this question as I can but if you need more information just let me know so I can add it and make this as clear as possible.
Your code has at least two separate attempts to download the data. Neither is really correct. The code also only works with JSON, not JSONP.
Try this:
NSURL *url = [NSURL URLWithString:#"https://getbible.net/json?p=James"];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data) {
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSRange range = [jsonString rangeOfString:#"("];
range.location++;
range.length = [jsonString length] - range.location - 2; // removes parens and trailing semicolon
jsonString = [jsonString substringWithRange:range];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError];
if (jsonResponse) {
// process jsonResponse as needed
} else {
NSLog(#"Unable to parse JSON data: %#", jsonError);
}
} else {
NSLog(#"Error loading data: %#", error);
}
}];
One problem is that the data you're downloading has extraneous information at the beginning and end. The JSON being delivered by your URL is:
({"book":[{"book_name":"James","book_nr":"59","chapter_nr":"3","chapter":{"16":{"verse_nr":"16","verse":"For where envying and strife is, there is confusion and every evil work."}}}],"direction":"LTR","type":"verse"});
As the error message you're seeing indicates: you need to remove the initial ( from the beginning of the string and the ); from the end so that your JSON will start with the dictionary that your code expects. You can do this by calling subdataWithRange: on your NSData object:
NSData* jsonData = [data subdataWithRange:NSMakeRange(1, data.length-3)];
NSDictionary* jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData
options:0
error:&error];
Just to update everyone, the NSURLRequest has been deprecated in iOS9. I tried the answer by #rmaddy, and I didn't receive anything either (just like what #lostAtSeaJoshua was encountering I guess). I have updated rmaddy's answer to reflect the NSURLSession implementation that has (I think) replaced NSURLRequest:
NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:#"http://somerandomwebsite.com/get.php?anotherRandomParameter=5"];
[[session dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
// handle response
if (data) {
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"stringJSONed: %#",jsonString);
//Do something with the received jsonString, just like in # rmaddy's reply
} else {
NSLog(#"Error loading data: %#", error);
}
}] resume];
Just a heads up notice, when I first ran it, it gave me the security error. What you need to do (if you are using http) is to add this to your plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
I have to mention that after the NSAllowArbitraryLoads key, there are most probably other keys and values, such as NSExceptionDomain. But they're not really relevant to this answer I think. If you need to look further, let me know and I will dig deeper :)

Making a GET request using NSURL not working

I am trying to get a simple GET request to work for my api. But it doesnt seem to work, and I am not sure why.
My code is as follows
Edit, also tried NSURLCredential But that does not seem to work either
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSString *urlAsString = #"https://www.test.com/api/v1/user/logout/";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error) {
if ([data length] >0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html); }
else if ([data length] == 0 && error == nil){
NSLog(#"Nothing was downloaded."); }
else if (error != nil){
NSLog(#"Error happened = %#", error); }
}];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
My API spits out json. So I should be getting a json object back that says
success: False
reason: 'Already Logged out'
But instead it gives me the following error
2013-03-07 16:24:44.038 test[8957:1d03] Error happened = Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x715db20 {NSErrorFailingURLKey=https://www.test.com/api/v1/user/logout/, NSErrorFailingURLStringKey=https://www.test.com/api/v1/user/logout/, NSUnderlyingError=0x7181cb0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)"}
Method 2
after some reseach, I found another way of sending get requests, and this method seems to work fine
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:#"https://www.test.com/api/v1/user/logout/"];
NSString *json = [NSString stringWithContentsOfURL:url
encoding:NSASCIIStringEncoding
error:&error];
if(!error) {
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData
options:kNilOptions
error:&error];
BOOL success = [[jsonDict objectForKey:#"success"] boolValue];
if (!success) {
NSString *reason = [jsonDict objectForKey:#"reason"];
NSLog(#"Cannot log out, as user %#", reason);
}
//NSLog(#"JSON: %#", jsonDict);
}else{
NSLog(#"\nJSON: %# \n Error: %#", json, error);
}
});
The solution to the problem was in the API itself. The API was supposed to send HTTPUnauthorized signal if the user is already logged out. And since that was the case, iOS was showing all these exceptions. when I dropped that and just sent back a simple json response, everything got fixed.

Resources