I am trying to upload image to the server. But i am getting error like-
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString CGImage]: unrecognized selector sent to instance 0x281a1d050'
*** First throw call stack:
libc++abi.dylib: terminating with uncaught exception of type NSException
*+(void)uploadImage: (NSArray *_Nullable)imagesArr productId: (NSString *_Nullable)productId featured:(BOOL)featured downloadProgress:(nullable void (^)(NSProgress * _Nullable downloadProgress))downloadProgressBlock completionHandler:(nullable void(^)(NSError * _Nullable error,id _Nullable response))completionHandler{
REQUEST_TYPE type = REQUEST_TYPE_JSON;
REQUEST_METHOD method = REQUEST_METHOD_POST;
NSMutableDictionary *headerDict = [[NSMutableDictionary alloc] init];
[headerDict setObject:[NSString stringWithFormat:#"Bearer %#",GET_TOKEN] forKey:#"Authorization"];
[headerDict setObject:[NSString stringWithFormat:#"application/json"] forKey:#"Content-Type"];
ServerConnection *connection = [ServerConnection getInstance];
NSString *createProducAPIURL = [NSString stringWithFormat:#"%#%#",URL_BASE,URL_PRODUCTIMAGE_UPLOAD];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
//
NSMutableArray *imageDictArr = [[NSMutableArray alloc] init];
int position = 0;
for (NSString *url in imagesArr) {
NSMutableDictionary *imageDict = [[NSMutableDictionary alloc] init];
[imageDict setObject:url forKey:#"src"];
[imageDict setObject:[NSNumber numberWithInt:position] forKey:#"position"];
[imageDictArr addObject:imageDict];
position++;
}
NSData *imageData = UIImageJPEGRepresentation(imagesArr[0], 0.5);
NSString *encodedString = [imageData base64EncodedStringWithOptions:kNilOptions];
NSLog(#"image: %#", imageData);
[parameters setObject:productId forKey:#"product_id"];
[parameters setObject:encodedString forKey:#"file"];
[connection dataTask:createProducAPIURL parameters:parameters requestType:type method:method headerDict:(NSDictionary *_Nullable)headerDict uploadProgress:^(NSProgress * _Nullable serveruploadProgress) {
} downloadProgress:^(NSProgress * _Nullable downloadProgress) {
downloadProgressBlock(downloadProgress);
} completionHandler:^(id _Nullable jsonSerializedData, NSError * _Nullable error) {
completionHandler(error,jsonSerializedData);
}];
}
-(void) dataTask:(NSString *_Nullable)URLString parameters:(NSDictionary *_Nullable)parameters requestType:(REQUEST_TYPE)type method:(REQUEST_METHOD)method headerDict:(NSDictionary *_Nullable)headerDict uploadProgress:(nullable void (^)(NSProgress * _Nullable uploadProgress))uploadProgressBlock downloadProgress:(nullable void (^)(NSProgress * _Nullable downloadProgress))downloadProgressBlock completionHandler:(nullable void (^)(id _Nullable jsonSerializedData, NSError * _Nullable error))completionHandler
{
NSMutableURLRequest *request;
// URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
URLString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:set];
switch (type) {
case REQUEST_TYPE_NORMAL:
request = [[AFHTTPRequestSerializer serializer] requestWithMethod:[self requestMethod:method] URLString:URLString parameters:parameters error:nil];
break;
case REQUEST_TYPE_JSON:
{
request = [[AFJSONRequestSerializer serializer] requestWithMethod:[self requestMethod:method] URLString:URLString parameters:nil error:nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
if(!error)
{
[request setHTTPBody:jsonData];
NSLog(#"Request body %#", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
}
else{
completionHandler(nil,error);
return;
}
}
break;
default:
request = [[AFHTTPRequestSerializer serializer] requestWithMethod:[self requestMethod:method] URLString:URLString parameters:parameters error:nil];
break;
}
if(!isNullObject(headerDict))
[request setAllHTTPHeaderFields:headerDict];
NSLog(#"TOKEN:%#",[USER_DEFAULTS objectForKey:kKeyToken]);
NSLog(#"REQUEST URL:%#",URLString);
NSLog(#"Request body %#", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
NSURLSessionDataTask *dataTask = [_manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(#"Upload Progress: %f",uploadProgress.fractionCompleted);
uploadProgressBlock(uploadProgress);
} downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(#"downloadProgress : %f",downloadProgress.fractionCompleted);
downloadProgressBlock(downloadProgress);
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if(!error)
{
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
// NSInteger statusCode = [HTTPResponse statusCode];
NSLog(#"URL:%#",HTTPResponse.URL);
NSLog(#"response:%#",string);
if([string rangeOfString:#"<!DOCTYPE html>"].location != NSNotFound){
string = [self stringByStrippingHTML:string];
NSData *resObj = [string dataUsingEncoding:NSUTF8StringEncoding];
id responseObject1 = [NSJSONSerialization JSONObjectWithData:resObj options:NSJSONReadingAllowFragments error:&error];
completionHandler(responseObject1,error);
}
else{
id responseObject1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
completionHandler(responseObject1,error);
}
}
else{
NSLog(#"error:%#",error);
id responseObject2 = nil;
if(responseObject!=nil)
{
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"response:%#",string);
responseObject2 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
}
completionHandler(responseObject2,error);
}
}];
[dataTask resume];
}*
Related
Unable to parse this json data to object. Same code i tried with other URL, working correct. Please Suggest where i am doing wrong?
-(void)callAPI{
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:#"https:s.json"]];
NSError *error=nil;
id response=[NSJSONSerialization JSONObjectWithData:data options:
NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];
if (error) {
NSLog(#"%#",[error localizedDescription]);
} else {
NSLog(#"%#",response);}}
Output The data couldn’t be read because it isn’t in the correct format.
I got the very perfect solution for your question which works fine now.Please check the below answer
- (void)callAPI
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"GET"];
[request setURL:[NSURL URLWithString:#"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"]];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * data,
NSURLResponse * response,
NSError * error) {
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"jsonString is: %#", jsonString);
NSData *dataCon = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonVal = [NSJSONSerialization JSONObjectWithData:dataCon options:0 error:nil];
if([jsonVal isKindOfClass:[NSDictionary class]]) {
NSLog(#"The response starts with NSDictionary");
NSArray *arrJsonVal = [jsonVal objectForKey:#"rows"];
NSMutableArray *arrTitle = [[NSMutableArray alloc]init];
NSMutableArray *arrDesc = [[NSMutableArray alloc]init];
NSMutableArray *arrImage = [[NSMutableArray alloc]init];
for(NSDictionary *dict in arrJsonVal) {
NSString *strTitle = [dict objectForKey:#"title"];
NSString *strDesc = [dict objectForKey:#"description"];
NSString *strImage = [dict objectForKey:#"imageHref"];
[arrTitle addObject:strTitle];
[arrDesc addObject:strDesc];
[arrImage addObject:strImage];
}
NSLog(#"arrTitle is - %#",arrTitle);
NSLog(#"arrDesc is - %#",arrDesc);
NSLog(#"arrImage is - %#",arrImage);
}else {
NSLog(#"The response starts with NSArray");
}
}] resume];
}
The Printed results are
After that
Then Array results are
Finally the results are
I was trying to load data for the table using values from server.I am using NSURLSession datatask with completion handler. Whenever it reaches the nsurlsession, it shows error.This is the code which i used for getting data.
- (void)geturl:(NSString *)urlvalue datavalues:(NSString *)string fetchGreetingcompletion:(void (^)(NSDictionary *dictionary, NSError *error))completion{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#?%#",common.getUrlPort,urlvalue,common.getappversion]];
NSLog(#"url=%#",url);
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest addValue:common.getauthtoken forHTTPHeaderField:#"Authorization"];
//Create POST Params and add it to HTTPBody
[urlRequest setHTTPMethod:#"GET"];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *connectionError) {
NSLog(#"Response:%# %#\n", response, connectionError);
if (data.length > 0 && connectionError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSString *code = [NSString stringWithFormat:#"%#",[greeting valueForKey:#"code"]];
if([code isEqualToString:#"-1"]){
[self loaderrorview:greeting];
}
else{
if (completion)
completion(greeting, connectionError);
}
}
else if(data == nil){
NSDictionary *errorDict=[[NSDictionary alloc]initWithObjectsAndKeys:#"Server Connection Failed",#"error", nil];
if (completion)
completion(errorDict,connectionError);
}
else
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
if (completion)
completion(greeting, connectionError);
}
}];
[dataTask resume];
}
The code which i used for getting data from server:
-(void)getdataexplore{
if (!common.checkIfInternetIsAvailable) {
[self.view makeToast:Nointernetconnection];
} else {
NSLog(#"There is internet connection");
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
[SVProgressHUD showWithStatus:#"Loading..."];
[apiservice geturl:loadexploredata datavalues:nil fetchGreetingcompletion:^(NSDictionary *dictionary, NSError *error) {
//NSLog(#"Test %# Error %#",dictionary,error);
if(error == nil){
authDictionary = dictionary;
[self loaddata];
}
else{
[SVProgressHUD dismiss];
[view_business makeToast:#"Request timed out" duration:2.0 position:CSToastPositionCenter];
}
}];
}
}
The code which i used for storing server data to array:
-(void)loaddata
{
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
[SVProgressHUD showWithStatus:#"Loading..."];
//[SVProgressHUD dismiss];
NSString *msg = [authDictionary valueForKey:#"msg"];
NSString *code = [NSString stringWithFormat:#"%#",[authDictionary valueForKey:#"code"]];
if([code isEqualToString:#"201"]){
NSDictionary *explore = [authDictionary valueForKey:#"explore_obj"];
arr_CBcategories = [explore valueForKey:#"cb_categories"];
[common setarrCBCaterory:arr_CBcategories];
arr_CBcategoryid = [arr_CBcategories valueForKey:#"id"];
[common setarrCateroryID:arr_CBcategoryid];
arr_CBcategorytitle = [arr_CBcategories valueForKey:#"title"];
[common setarrCaterorytitle:arr_CBcategorytitle];
arr_CBcategoryslug = [arr_CBcategories valueForKey:#"slug"];
[common setarrCateroryslug:arr_CBcategoryslug];
arr_CBcategoryimage = [arr_CBcategories valueForKey:#"image"];
[common setarrCateroryimage:arr_CBcategoryimage];
arr_CBcategorycode = [arr_CBcategories valueForKey:#"code"];
}
I am getting error like "Unable to run main thread". Any solution for this.
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)
I wrote a function to fetch an NSDictionary from a URL.
[Data loadFromAPI:#"http://example.com/api" withSuccess:^(id data) {
NSMutableDictionary *result = (NSDictionary *)data;
CLS_LOG(#"result: %#", result);
} failure:^(NSError *error) {
CLS_LOG(#"Error: %#", error);
}];
The function it calls is the one below:
typedef void (^Success)(id data);
typedef void (^Failure)(NSError *error);
+ (void)loadFromAPI:(NSString *)apiURL withSuccess:(Success)success failure:(Failure)failure {
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:apiURL]];
NSMutableURLRequest *mutableRequest = [request mutableCopy];
request = [mutableRequest copy];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [JSONResponseSerializerWithData serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *jsonArray = (NSArray *)responseObject ;
NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:
[self now], #"time",
jsonArray, #"response",
nil];
CLS_LOG(#"Result is: %#", result);
success(result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure?failure(error):nil;
}];
[operationQueue setMaxConcurrentOperationCount:1];
[operationQueue addOperations:#[operation] waitUntilFinished:NO];
}
Inside the function CLS_LOG(#"Result is: %#", result); returns the data returned. However, where I call the function CLS_LOG(#"result: %#", result); returns null. What am I doing wrong?
As it turns out [self now] returned null, so the NSDictionary wasn't being set properly.
The problem is
NSMutableDictionary *result = (NSDictionary *)data;
you cant directly do that, i wonder why you dont have a warning for that..
NSMutableDictionary *result = [[NSMutableDictionary alloc] initWithDictionary:(NSDictionary *)data];
will probably solve the problem...
hi friend i am beginner for objective-c.i have slow response from server side due to synchronous call. i analysed in google the call may be asynchronous means the response speed will be high, but i don't know much about NSURLConnection and GCD. so please help me how to change my call asynchronous . see my code below`
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString* oldToken = [self deviceToken];
NSString *newToken = [[[[deviceToken description]stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"My token is: %#", newToken);
[self setDeviceToken:newToken];
if (![newToken isEqualToString:oldToken])
{
[self calur:newToken];
}
}
- (NSString*)deviceToken{
return [[NSUserDefaults standardUserDefaults] stringForKey:#"deviceid"];
}
- (void)setDeviceToken:(NSString*)token{
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"deviceid"];
}
//This function used to store a notification device id to our notification databae
-(void)calur:(NSString *)device
{
NSString *post =[NSString stringWithFormat:#"deviceId=%#",device];
NSString *hostStr = #"https://myserver.com/Ver_2_0/notification/check.php?";
NSError *error = nil;
NSString *nocon=[NSString stringWithContentsOfURL:[NSURL URLWithString:hostStr]encoding:NSUTF8StringEncoding error:&error];
if (nocon == nil)
{
NSLog(#"NO Connection");
}
else
{
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"hostStr=%#",hostStr);
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"dataURL=%#",dataURL);
// NSData *dataurl=dataURL;
if([serverOutput isEqualToString:#"Token Updated Successfully"])
{
NSLog(#"badge updated");
}
else
{
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"not registered");
}
[serverOutput release];
}
}`
if (nocon == nil)
{
NSLog(#"NO Connection");
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"hostStr=%#",hostStr);
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"dataURL=%#",dataURL);
// NSData *dataurl=dataURL;
if([serverOutput isEqualToString:#"Token Updated Successfully"])
{
NSLog(#"badge updated");
}
else
{
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"not registered");
}
[serverOutput release];
});
}
a little snippet:
#import "AFNetworking.h"
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:self.value, #"POSTvar", nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: [NSURL URLWithString:#"http://your.address"]];
NSURLRequest *request = [client requestWithMethod:#"POST" path:nil parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// do some with JSON
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
});
AFNetworking github