I have this method to get the contents of an URL on TV:
-(void)placeGetRequestForDeveloperID:(NSString *)developerID andRunOnCompletion:(void (^)(NSData *data, NSURLResponse *response, NSError *error))ourBlock {
NSString *urlString = [NSString stringWithFormat:#"https://itunes.apple.com/lookup?id=%#&entity=software", developerID];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
[session dataTaskWithRequest:request completionHandler:ourBlock];
}
The completion block is never called.
NSURLSession is allowed on tvOS. Is there something I have to set on the project, like entitlements or something on the Info.plist to make this work? Is this code OK?
Thanks!
By default, when you create the task, it's suspended. You have to start the task by calling resume.
[[session dataTaskWithRequest:request completionHandler:ourBlock] resume]
You have to resume the task to start the API call.
You can try the API call as like below too.
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *apiCall = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
}];
[apiCall resume];
Related
I am new to Mac application development and i am working on fixing the deprecation issues present in the application. I am using XCode 11.3 in Mojave MacOS 10.14 and Our application contains the following line of code
[NSURLConnection sendSynchronousRequest:request returningResonse:response error:Error]
A warning message getting displayed as sendSynchronousRequest is deprecated and it is suggesting to use [NSURLSession dataTaskWithRequest:completionHandler:] .
so i have implemented the following code
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:#"MyURLHere"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
}
}];
[dataTask resume];
i found that data is being returned as nil always. When i debugged the code, i found that even [NSURLSessionConfiguration defaultSessionConfiguration] is being returned as nil. Can you please suggest what needs to be done in order to fix these issues?
I am attempting to upload a PNG file to a device, using NSURLDataTask and a "POST" request.
However my attempts always conclude with the device returning a 400 HTTP error code in the response.
My Upload code looks like this:
-(void)uploadMedia:(NSData*)mediaData withName:(NSString*)name andID:(NSString*)mediaID
{
NSString *urlString;
NSString *appToken [self retrieveAppToken];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
appToken, #"km-device-auth",
#"application/octet-stream", #"Content-Type",
nil];
sessionConfiguration.HTTPAdditionalHeaders = dict;
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
urlString = [NSString stringWithFormat:#"https://%#:7788/Media?name=%#&id=%#",_strIP,name,mediaID];
NSLog(#"Attemptive Upload URL:%#",urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
request.HTTPBody = mediaData;
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"My respone:%#:%#",response,data);
}];
[postDataTask resume];
}
SOLVED
My headers also required a value for "Content-MD5" which was missing.
I am trying to fetch JSON data and parse it using NSUrl session but getting null every time - Also in addition to that i want o show all data in table view
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"text/plain" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"text/plain" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"GET"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"Value", #"Key", nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Resopnse == %#",response);
if (response != nil) {
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"JSon dict === %#",jsonDict);
}
}];
[postDataTask resume];
May I know what i am doing wrong is anything other good way to do same?
Try following code.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"]];
[request setHTTPMethod:#"GET"];
[request addValue:#"text/plain" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"text/plain" forHTTPHeaderField:#"Accept"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSData * responseData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"requestReply: %#", jsonDict);
}] resume];
Please use the below code for the same. Hope it will solve your problem.
NSString *strUrl = [NSString stringWithFormat:yourUrl];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *dicResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(#"%#",dicResponse);
}
}];
How we call sync call But the give response asynch.here is my code.
NSURL *URL = [NSURL URLWithString:#"http://example.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
// ...
}];
[task resume];
We can't and we never could.
The previous approach was halting the execution of the tread, continuing after getting the data or after a timeout.
I want to post a request to server. It is working fine if I am using NSURLSessionDataTask. But underneath I need to use AFNetworking as my whole application is using it. But when I am trying to hit the same service in AFHTTPSessionManager with POST method, It is giving me request time out.
Below are both the codes.
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"BASE URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *postString = #"1";
NSData *data = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}];
[postDataTask resume];
AFNetworking kit version :-
AFHTTPSessionManager *client = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:#"BASE URL"]];
NSDictionary *request = #{#"Content-Type":#"application/json",
#"Accept":#"application/json",
};
NSString *postString = #"1";
NSData *data = [postString dataUsingEncoding:NSUTF8StringEncoding];
[client POST:#"" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithHeaders:request body:data];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"%#",error);
}];
Please help me in implementing it in right way.
I solved this problem by creating my own request and give its configuration to AFURLSessionManager and then holding my own NSURLSessionUploadTask object.
Thanks