Here's my code
AFHTTPSessionManager *manger = [[AFHTTPSessionManager alloc] init];
[manger GET:requestUrl parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
I got two error from Xcode.
Unknown type name 'id'
Incompatible block pointer types sending 'void (^)(NSURLSessionDataTask * _Nonnull __strong, int)' to parameter of type 'void (^ _Nullable)(NSURLSessionDataTask * _Nonnull __strong, id _Nullable __strong)'.
Why is this happen?I had imported AFNetworking file in my header file.My Xcode version is 8.2,and AFNetworking version is 3.1.When I put this code snippet in my other project,there was no error.That was really confused me.Anyone can help?
I used Carthage to import AFNetwoking,still the same error.:(
Final solution:I recreate the project.And migrate the old code to new project.It works.But still know the reason why the old version code not work.
your method should like this
-(void)callWebserviceWithParams:(NSMutableDictionary *)_params
action:(NSString *)_action
success:(void (^)(id))_success
failure:(void (^)(NSError *))_failure
{
if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
//AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSString *url = [BASE_URL stringByAppendingString:_action];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
[manager POST:url parameters:_params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"response = %#", responseObject);
if( _success )
{
_success( responseObject ) ;
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error = %#", error);
if( _failure )
{
_failure( error) ;
}
}];
}
}
Related
I have done the following code to get car_image from response obtained on hitting api.I have a url as value for key car_image.Till,now everything works fine.
Code:
-(void)callService{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"text/html",#"application/json", nil];
NSMutableDictionary *dict = [NSMutableDictionary new];
[dict setValue:#561 forKey:#"did"];
[manager POST:#"http://demo.esenseit.in/Alec1-Admin-Panel-and-API/alec_api/index.php?flag=get_car_list" parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"response %#",responseObject);
responseArr = [responseObject valueForKey:#"data"];
NSString *urlstr=[[responseArr valueForKey:#"car_image"]objectAtIndex:1];
NSLog(#"value of urlstr %#",urlstr);
// NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:urlstr]];
NSError* error = nil;
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlstr] options:NSDataReadingUncached error:&error];
if (error) {
NSLog(#"Error is %#", [error localizedDescription]);
} else {
NSLog(#"Data has loaded successfully.");
}
NSLog(#"value of url %#",[NSURL URLWithString:urlstr]);
NSLog(#"value of data %#",data);
dispatch_async(dispatch_get_main_queue(), ^{
});
}
failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
NSLog(#"request failed %#",error);
}];
}
Problem:
The value of data returns as null. I am not able to understand when string, url are all returning their values nicely, then why only data is creating null result.
Log Values:
1)value of urlstr demo.esenseit.in/Alec1-Admin-Panel-and-API/alec_api/upload/car_8_1514810479.jpg
2)Error is The file “car_8_1514810479.jpg” couldn’t be opened.
3)value of url demo.esenseit.in/Alec1-Admin-Panel-and-API/alec_api/upload/car_8_1514810479.jpg
4)value of data (null)
MY CODE IS FOR AFNETWOKING 3.0
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"multipart/form-data"];
[manager.requestSerializer setTimeoutInterval:30];
[manager POST:URLString parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if([responseObject isKindOfClass:[NSDictionary class]]) {
RequestCompletionHandlerBlock(responseObject);
}
else {
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
RequestCompletionHandlerBlock(response);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Error Is %#",error.description);
RequestFailedHandlerBlock(#{#"error " :error.description});
}];
RESPONCE IS :
NSLocalizedDescription=Request failed: unacceptable content-type: text/html
try this
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setTimeoutInterval:30];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST: URLString parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"all data=%#",responseObject);
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
How to write the code to sending POST method for the below JSON format using Afnetworking.
{
Media
{
Photo : image.jpg,
UserId : 2
},
Personal
{
Name : aaa,
Age : 30
},
Education
{
College : xxx,
Course : yyy
},
}
Obviously that's not quite the actual format, but we can guess what you might have meant. Clearly, if those numeric values (the user id and age) are expected as strings, then quote then, but hopefully it illustrates what the Objective-C representation of that dictionary might look like:
NSDictionary *parameters = #{#"Media": #{#"Photo": #"image.jpg", #"UserId": #2}, #"Personal": #{#"Name": #"aaa", #"Age": #30}, #"Education": #{#"College": #"xxx", #"Course": #"yyy" }};
Then you can post it as JSON like so:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:#"https://yoururl.com" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"responseObject = %#", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error %#", error);
}];
And if your server doesn't support HTTPS, but only HTTP, then you might have to alter your Info.plist's "App Transport Security Settings" to "Allow Arbitrary Loads".
Firstly make a dictionary of params you want to send
NSDictionary *params = #{
#"contact_no":#"9898989898",
#"password":#"••••••••••"
};
Then write the following code
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
operationManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/html", nil];
[operationManager POST:urlString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(#"%#",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error){
if (failure)
NSLog(#"%#",error.localizedDescription);
}];
You can neglect the line in which i am setting the acceptableContentTypes.
Hope this will help.
I am sending array as a parameter in AFNetworking GET Request.
My code is as follows:
- (void)getProductSearchResult:(NSString *)locale andSearchDict:(NSDictionary *)dictSearch{
NSString *strURL = [NSString stringWithFormat:#"%#/%#/search?%#",BASEURL,locale,APIFORMAT];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager GET:strURL parameters:dictSearch success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *jsonDict = (NSDictionary *)responseObject;
if ([jsonDict isKindOfClass:[NSDictionary class]] || [jsonDict isKindOfClass:[NSMutableDictionary class]]) {
if (self.delegate && [self.delegate respondsToSelector:#selector(API_ProductSearch_didSuccess:)]) {
[self.delegate API_ProductSearch_didSuccess:jsonDict];
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (self.delegate && [self.delegate respondsToSelector:#selector(api_ProductSearch_didFailWithError:)]) {
[self.delegate api_ProductSearch_didFailWithError:[NSError description]];
}
}];
}
The dictionary which I pass as parameter is as follows:
{
"brand_filter" = (
1
);
"category_filter" = (
438
);
"max_price" = "47.37188";
"min_price" = "1.95";
"price_currency" = USD;
"supplier_filter" = (
"Aakron Line"
);
}
URL which created is shown like
http://demo.aakronline.ca/app_dev.php/api/v1/en_us/search?_format=json&brand_filter[]=1&category_filter[]=438&max_price=48.04479&min_price=2.622917&price_currency=USD&supplier_filter[]=Aakron%20Line
The problem area in URL is array is not passed in proper format i.e.
brand_filter[]=1&category_filter[]=438 instead of brand_filter=[1]&category_filter=[438]
Can anyone tell me how to solve this mistake?
But I am not getting the successful response.
In afnetworking 3.0, instead of AFHTTPRequestOperationManager use AFHTTPSessionManager
NSString *strUrl = [NSString stringWithFormat:#"%#/%#/search?%#",BASEURL,locale,APIFORMAT];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:strUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"value: %#",responseObject);
//other code as it is
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Error: %#",error);
}];
I tried to make GET HTTP response. I need to get the html code for the subsequent parsing, but responseObject is nil.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager GET:#"http://www.example.com/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error;
HTMLParser *parser = [[HTMLParser alloc] initWithString:responseObject error:&error];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
For get html code we will need to build a custom response serializer to decode the NSData response from the web server into a NSString. We will need to subclass AFHTTPResponseSerializer and implement the following method:
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
Why for example you have not use this solution below instead of subcalssing. It does the same thing, but you don't need to create additional files, just for overload one method.
So you can just add encoding your responseObjet in the block for example, and it will work as well. I am using POST in my example but it should work with GET in the same way but without parameters, but idea of the just conversation.
+ (void)makeRequestWithParams:(NSDictionary *)params
success:(OperationCompletionBlock)success
failure:(OperationCompletionBlock)failure
{
NSString *path = #"http://www.example.com/";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFCompoundResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString* encodedString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", encodedString);
success(nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
failure(nil);
}];
}