NSURLConnection Asyncronous Request returns null - objective-c

Followed a recently made YouTube tutorial try connecting to web address asynchronously.
Retuning null for the response, but the data length is greater than 0. I've seen other code that does both null & length checking, which I didn't throw, just NSLog'd them.
#implementation ViewController
-(void)fetchAddress:(NSString *)address {
NSLog(#"Loading Address: %#", address);
[iOSRequest requestToPath:address onCompletion:^(NSString *result, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
[self stopFetching:#"Failed to Fetch"];
NSLog(#"%#", error);
} else {
[self stopFetching:result];
NSLog(#"Good fetch: %#", result);
}
});
}];
}
- (IBAction)fetch:(id)sender {
[self startFetching];
[self fetchAddress:self.addressField.text];
NSLog(#"Address: %#", self.addressField.text);
}
-(void)startFetching {
NSLog(#"Fetching...");
[self.addressField resignFirstResponder];
[self.loading startAnimating];
self.fetchButton.enabled = NO;
}
-(void)stopFetching:(NSString *)result {
NSLog(#"Done Fetching %#", result);
self.outputLabel.text = result;
[self.loading stopAnimating];
self.fetchButton.enabled = YES;
}
#implementation iOSRequest
+(void)requestToPath:(NSString *)
path onCompletion:(RequestCompletionHandler)complete {
NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path]
cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
timeoutInterval:10];
NSLog(#"path: %# %#", path, request);
[NSURLConnection sendAsynchronousRequest:request
queue:backgroundQueue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *result = [[NSString alloc] initWithData:
data encoding:NSUTF8StringEncoding];
if (complete) {
complete(result, error);
NSLog(#"result: %# %lu %#", result, (unsigned long)[data length], error);
}
}];
}
request is http://www.google.com>
response is null
data length is 13644
Not sure what is wrong... any suggestions?

Thanks to Josh Caswell for pointing in the right direction, but allowing me to figure it out myself.
Changed the initWithData encoding from NSUTF8StringEncoding to NSASCIIStringEncoding.
[NSURLConnection sendAsynchronousRequest:request
queue:backgroundQueue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *result = [[NSString alloc] initWithData:
data encoding:NSASCIIStringEncoding];
if (complete) {
complete(result, error);
NSLog(#"result: %# %lu %#", result, (unsigned long)[data length], error);
}
}];

Related

The operation couldn't be completed (nsurlErrorDomain error -1012)

I have checked and applied it's all possible answers but not getting any success because I couldn't find the reason.
I am calling an API and sometimes it is working fine but some time it is giving me "The operation couldn't be completed (nsurlErrorDomain error -1012)" error.
My API calling code:
I have created this global method to call APIs. For this, I have created a singleton class.
-(void)getDispatchDetail:(NSString *)strDispatchId successBlock:(void(^)(NSDictionary *response))successBlock withFailureBlock:(FailureBlock)failureBlock{
NSString *urlString = [NSString stringWithFormat:#"%#%#",BASE_URL,END__POINT_getDispatchDetail];
[self MethodType:POST URL:urlString parameters:#{#"DispatchId":strDispatchId?strDispatchId:#""} withCookies:nil completionBlockWithSuccess:^(id responseObject, NSURLResponse *urlResponse) {
successBlock(responseObject);
} failure:^(NSError *error) {
[ProgressHUD dismiss];
failureBlock(error);
}];
}
-(void)MethodType:(METHOD_TYPE)methodType
URL:(NSString *)urlString
parameters:(NSDictionary *)param
withCookies:(BOOL)isCookies completionBlockWithSuccess:(void (^)(id responseObject, NSURLResponse *urlResponse))success
failure:(void (^)(NSError *error))failureRequest
{
if (isCookies){
//[ProgressHUD show:kSTRING_LOADING Interaction:NO];
}
/**
Create URl based on the Request Type
**/
NSURL *url;
switch (methodType) {
case GET:
if (param) {
NSString *strDict = [self stringFromDictionary:param];
NSString *strURL = [NSString stringWithFormat:#"%#?%#",urlString,strDict];
strURL = [strURL stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
url = [NSURL URLWithString:strURL];
break;
}
url = [NSURL URLWithString:urlString];
break;
case PUT:
case POST:
case DELETE:
url = [NSURL URLWithString:urlString];
break;
default:
break;
}
/**
Create Reuqest based on the Request Type
**/
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
switch (methodType) {
case GET:
[req setHTTPMethod:#"GET"];
break;
case POST:
{
[req setHTTPMethod:#"POST"];
NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
failureRequest(error);
}
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:postData];
}
break;
case PUT:
{
[req setHTTPMethod:#"PUT"];
NSError *error = nil;
if (param != nil) {
NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&error];
[req setHTTPBody:postData];
}
if (error) {
failureRequest(error);
}
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
}
break;
case DELETE:
{
[req setHTTPMethod:#"DELETE"];
}
break;
default:
break;
}
//self.strAccessToken = #"Token ab6520a0805b11e82c750034548b74d02464e900";
//self.strAccessToken = [ETDataModelClass getUserAccessToken];
if ([[NSUserDefaults standardUserDefaults] valueForKey:API_PARAM_USER_ACCESS_TOKEN] != nil) {
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:kUserLoginTokenAndData];
NSString *tokenType = [dict objectForKey:#"token_type"];
self.strAccessToken = [NSString stringWithFormat:#"%# %#",tokenType,[[NSUserDefaults standardUserDefaults] valueForKey:API_PARAM_USER_ACCESS_TOKEN]];
// [self.strAccessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[req setValue:self.strAccessToken forHTTPHeaderField:API_ACCESS_TOKEN];
}
NSLog(#"ReqType : %# URL : %#, Param : %#", [self getMethodTypeName:methodType], url, param);
NSLog(#"User Token : %#",_strAccessToken);
[req setTimeoutInterval:60.0];
[NSURLConnection sendAsynchronousRequest:req
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *responseHeader, NSData *responseBody, NSError *error)
{
NSError *errorData = nil;
NSLog(#"Response Header : %#", responseHeader);
NSLog(#"Response : %#", [[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
id responseObject1;
if(![responseBody isKindOfClass:[NSNull class]] && responseBody != nil)
responseObject1 = [NSJSONSerialization JSONObjectWithData:responseBody options:NSJSONReadingMutableLeaves error:&errorData];
else{
[ProgressHUD dismiss];
[Utility showAlertMessage:#"No Internet Connection. Make sure your device is connected to the internet." WithTitle:#""];
return ; // When response body nil we will return the control
}
// NSLog(#"Server Response ===> :\n %#", responseObject1);
// NSLog(#"Server Error ===> :\n %#", errorData);
if (error) {
if([responseObject1 isKindOfClass:[NSDictionary class]]){
if([[responseObject1 objectForKey:API_Alert_MESSAGE] isEqualToString:kAutologoutResponseFromServer]){
NSLog(#" Response ===== %# =====", responseObject1);
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationAutoLogout object:nil userInfo:responseObject1];
}
}
[ProgressHUD dismiss];
failureRequest(error);
return ;
}
else {
//[ProgressHUD dismiss];
if (!errorData) {
if (responseObject1 == nil) {
return [Utility showAlertMessage:NO_DATA_AVAILABLE WithTitle:#""];
}
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) responseHeader;
long statusCode = httpResponse.statusCode;
NSLog(#"statusCode : %ld",statusCode);
switch (statusCode) {
case API_STATUS_CODE_200: case API_STATUS_CODE_402:
if (success) {
success(responseObject1,responseHeader);
}
break;
case API_STATUS_CODE_500: case API_STATUS_CODE_400:
NSLog(#"responseHeader : %#",responseHeader);
NSLog(#"responseBody : %#",[[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
NSLog(#"error : %#",error.localizedDescription);
NSLog(#"%#",[[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
[Utility showAlertMessage:SERVER_ERROR WithTitle:#""];
[ProgressHUD dismiss];
break;
case API_STATUS_CODE_403:{
NSLog(#"auto logout warning : %#",responseBody);
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationAutoLogout object:nil userInfo:responseObject1];
[ProgressHUD dismiss];
break;
}
default:
NSLog(#"responseHeader : %#",responseHeader);
NSLog(#"responseBody : %#",[[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
NSLog(#"error : %#",error.localizedDescription);
NSLog(#"%#",[[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
if([responseObject1 isKindOfClass:[NSDictionary class]])
if([responseObject1 valueForKey:API_Alert_MESSAGE] && [responseObject1 valueForKey:API_Alert_MESSAGE] != nil)
[Utility showAlertMessage:[responseObject1 valueForKey:API_Alert_MESSAGE] WithTitle:#""];
[ProgressHUD dismiss];
break;
}
}
else{
failureRequest(errorData);
}
}
}];
}

Facing an issue with NSURLSessionDataTask with SynchronousRequest in objective-c

Here is my working code with NSURLConnection sendSynchronousRequest :
+ (Inc*)getData:(NSString*)inUUID {
NSString* urlString = [NSString stringWithFormat:#"/inc/%#", incUUID];
NSURLRequest* request = [[HttpRequest requestWithRelativePath:urlString] toNSMutableURLRequest];
NSDictionary* json = [self getJSONForRequest:request];
return [Inc incFromDictionary:json];
}
+ (NSDictionary*)getJSONForRequest:(NSURLRequest*)request {
NSData* responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
return [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
}
But, sendSynchronousRequest:request is deprecated.
So that, I used NSURLSessionDataTaskinstead of sendSynchronousRequest. Here, is the code which I implemented:
+ (Inc*)getData1:(NSString*)inUUID {
NSString* urlString = [NSString stringWithFormat:#"/in/%#", inUUID];
NSURLRequest* request = [[HttpRequest requestWithRelativePath:urlString] toNSMutableURLRequest];
//NSDictionary* json = [self getJSONForRequest1:request];
__block NSDictionary* json;
dispatch_async(dispatch_get_main_queue(), ^{
[self getJsonResponse1:request success:^(NSDictionary *responseDict) {
json = [responseDict valueForKeyPath:#"detail"];;
//return [Inc incFromDictionary:json];
} failure:^(NSError *error) {
// error handling here ...
}];
});
return [Inc incFromDictionary:json];
}
+ (void)getJsonResponse1:(NSURLRequest *)urlStr success:(void (^)(NSDictionary *responseDict))success failure:(void(^)(NSError* error))failure
{
NSURLSessionDataTask *dataTask1 = [[NSURLSession sharedSession] dataTaskWithRequest:urlStr completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
NSLog(#"%#",data);
if (error)
failure(error);
else {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",json);
success(json);
}
}];
[dataTask1 resume]; // Executed First
}
The problem is return statement call in getData1 before finish the api call.
Thanks in advance.
As mentioned in the comments you need a completion handler.
Something like this (untested):
+ (void)getData1:(NSString*)inUUID success:(void (^)(NSDictionary *responseDict))success failure:(void(^)(NSError* error))failure {
NSString* urlString = [NSString stringWithFormat:#"/in/%#", inUUID];
NSURLRequest* request = [[HttpRequest requestWithRelativePath:urlString] toNSMutableURLRequest];
[self getJsonResponse1:request success:^(NSDictionary *responseDict) {
NSDictionary* json = [responseDict valueForKeyPath:#"detail"];
success(json);
} failure:^(NSError *error) {
failure(error);
}];
}
+ (void)getJsonResponse1:(NSURLRequest *)urlStr success:(void (^)(NSDictionary *responseDict))success failure:(void(^)(NSError* error))failure
{
NSURLSessionDataTask *dataTask1 = [[NSURLSession sharedSession] dataTaskWithRequest:urlStr completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
NSLog(#"%#",data);
if (error)
failure(error);
else {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",json);
success(json);
}
}];
[dataTask1 resume]; // Executed First
}
And to call
[MyClass getData1:#"asdf" success:^(NSDictionary *responseDict) {
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *json = [responseDict valueForKeyPath:#"detail"];
Inc *inc = [Inc incFromDictionary:json];
// do something witrh `inc`
});
} failure:^(NSError *error) {
// error handling here ...
}];
Consider to use instances and instance methods of your class(es) rather than only class methods.

iOS - Downloading Video Data from Parse

I am trying to download a PFFile which is a tfss file(?). It gets opened as a text file. This is the code I use for retrieveing the data:
-(void) queryVideoWithDictionary:(NSDictionary *)dictionary {
PFQuery *videoQuery = [PFQuery queryWithClassName:#"EventVideos"];
[videoQuery whereKey:#"objectId" equalTo:[dictionary objectForKey:#"videoId"]];
[videoQuery findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
if (!error) {
PFFile *videoFile = [results[0] objectForKey:#"video"];
[videoFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSURL *movieURL = [NSURL fileURLWithPath:dataString];
NSMutableDictionary *videoDictionary = [NSMutableDictionary dictionaryWithObject:data forKey:[dictionary objectForKey:#"videoId"]];
[self.videoArray addObject:videoDictionary];
NSLog(#"video array count: %ld", self.videoArray.count);
NSLog(#"dataString: %#", dataString);
// NSLog(#"movieURL: %#", movieURL);
[self.player setItemByStringPath:dataString];
[self.player play];
});
}];
} else {
NSLog(#"error");
}
}];
}
When dataString gets logged, it returns null, so I don't know how to get the data and play it as a video. It is saved as a QuickTimeMovie by the way.
I use SCRecorder to play and record videos.
Edit: data is definitely not nil, I still don't know how to solve this issue.

Making stringWithContentsOfURL asynchronous - Is it safe?

I attempted to make -[NSString stringWithContentsOfURL:encoding:error:] asynchronous, by running it a-synchronically from a background thread:
__block NSString *result;
dispatch_queue_t currentQueue = dispatch_get_current_queue();
void (^doneBlock)(void) = ^{
printf("done! %s",[result UTF8String]);
};
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
(unsigned long)NULL), ^(void) {
result = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com/"] encoding:NSUTF8StringEncoding error:nil];
dispatch_sync(currentQueue, ^{
doneBlock();
});
});
Its working fine, and most importantly, its asynchronous.
My question is if it's safe to do this, or could there be any threading problems etc.?
Thanks in advance :)
That should be safe, but why reinvent the wheel?
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.google.com"]];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// etc
}];
You can also use:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSString *searchResultString = [NSString stringWithContentsOfURL:[NSURL URLWithString:searchURL]
encoding:NSUTF8StringEncoding
error:&error];
if (error != nil) {
completionBlock(term,nil,error);
}
else
{
// Parse the JSON Response
NSData *jsonData = [searchResultString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *searchResultsDict = [NSJSONSerialization JSONObjectWithData:jsonData
options:kNilOptions
error:&error];
if(error != nil)
{
completionBlock(term,nil,error);
}
else
{
//Other Work here
}
}
});
But yes, it should be safe. I've been told though to use NSURLConnection instead due to error calls and such when communicating via the internet. I'm still doing research into this.
-(void)loadappdetails:(NSString*)appid {
NSString* searchurl = [#"https://itunes.apple.com/lookup?id=" stringByAppendingString:appid];
[self performSelectorInBackground:#selector(asyncload:) withObject:searchurl];
}
-(void)asyncload:(NSString*)searchurl {
NSURL* url = [NSURL URLWithString:searchurl];
NSError* error = nil;
NSString* str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
if (error != nil) {
NSLog(#"Error: %#", error);
}
NSLog(#"str: %#", str);
}

Returning NSDictionary from async code block? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
returning UIImage from block
Hi I'm trying to return dictionary of json twitter data so i can use it in my application. How ever it is being called from a async block. I can not save it or return it any thoughts?
-(NSDictionary *)TweetFetcher
{
TWRequest *request = [[TWRequest alloc] initWithURL:
[NSURL URLWithString: #"http://search.twitter.com/search.json?
q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"] parameters:nil
requestMethod:TWRequestMethodGET];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse
*urlResponse,
NSError *error)
{
if ([urlResponse statusCode] == 200)
{
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData
options:0 error:&error];
//resultsArray return an array [of dicitionaries<tweets>];
NSArray* resultsArray = [dict objectForKey:#"results"];
for (NSDictionary* internalDict in resultsArray)
NSLog([NSString stringWithFormat:#"%#", [internalDict
objectForKey:#"from_user_name"]]);
----> return dict; // i need this dictionary of json twitter data
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}
Thnx in advance!
I feel like I've written a ton of this async code lately.
- (void)tweetFetcherWithCompletion:(void(^)(NSDictionary *dict, NSError *error))completion
{
NSURL *URL = [NSURL URLWithString:#"http://search.twitter.com/search.json?q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"];
TWRequest *request = [[TWRequest alloc] initWithURL:URL parameters:nil requestMethod:TWRequestMethodGET];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if ([urlResponse statusCode] == 200) {
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
if (error) {
completion(nil, error);
return;
}
//resultsArray return an array [of dicitionaries<tweets>];
NSArray* resultsArray = [dict objectForKey:#"results"];
for (NSDictionary* internalDict in resultsArray)
NSLog(#"%#", [internalDict objectForKey:#"from_user_name"]);
completion(dict, nil);
}
else {
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
completion(nil, error);
}
}];
}
So, instead of calling self.tweetDict = [self TweetFetcher];, you would call it this way.
[self tweetFetcherWithCompletion:^(NSDictionary *dict, NSError *error) {
if (error) {
// Handle Error Somehow
}
self.tweetDict = dict;
// Everything else you need to do with the dictionary.
}];