I have this code;
NSString *post = [NSString stringWithFormat:#"latitude=%lf&longitude=%lf&provider=network&accuracy=%lf&hiz=%lf&retrieveTime=%#",
locationManager.location.coordinate.latitude,
locationManager.location.coordinate.longitude,
locationManager.location.horizontalAccuracy,
locationManager.location.speed,
dateString];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *sUrl = [[NSUserDefaults standardUserDefaults] stringForKey:#"serviceUrl"];
NSString *swoclString = [NSString stringWithFormat:#"%#/saveLocation.php", sUrl];
[request setURL:[NSURL URLWithString:swoclString]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn) {
NSLog(#"Location Save Successfully");
} else {
NSLog(#"Location Save Error");
}
I can receive the data in the server side. And on the iOS side I can see the log "Location Save Successfully".
How can I receive the response from the server without implementing other methods?
Use NSURLSession instead of NSURLConnection to post your data to the Server. Below is an example how you can post JSON.
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"<YOUR-URL-STRING>"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:<YOUR_JSON_DATA> options:NSJSONWritingPrettyPrinted error:&error];
NSString *tmp = [[NSString alloc]initWithData:postData encoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *resp = (NSHTTPURLResponse *) response;
NSLog(#"%li",(long)resp.statusCode);
if(resp.statusCode==200){
NSMutableArray *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
}];`
The block is used to return the response by the server. For example the HTTP-Status Code and the response data. If you use json you can convert the Data with the NSJSONSerialization class.
If you are using latest ios coding standards you must have to use URLSession object to send any request to the API calls because DEPRECATED: The NSURLConnection class should no longer be used. NSURLSession is the replacement for NSURLConnection. But still, if you want to continue with an old procedure, there are three ways to send API request.
P1:
-(void)procedure1{
NSURLRequest *requestObject = nil; /** replace with your request object **/
NSURLResponse *serverResponse = nil;
NSError *connectError = nil;
/* thread bloker request */
NSData *responseData = [NSURLConnection sendSynchronousRequest:requestObject returningResponse:&serverResponse error:&connectError];
if (connectError == nil) {
//parse server response data (i.e, json or xml)
}else{
/* handle connection error */
}
}
P2:
-(void)procedure2{
NSURLRequest *requestObject = nil; /** replace with your request object **/
/* thread free request */
[NSURLConnection sendAsynchronousRequest:requestObject queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError == nil) {
//parse server response data (i.e, json or xml)
}else{
/* handle connection error */
}
}];
}
P3:
the last one is a bit different than the other two,
#interface TestViewController ()<NSURLConnectionDelegate>
#property (nonatomic, retain) NSMutableData* responseData;
#end
-(void)procedure3{
NSURLRequest *requestObject = nil; /** replace with your request object **/
NSURLConnection *connectionObject = [NSURLConnection connectionWithRequest:requestObject delegate:self];
[connectionObject start];
}
here in this procedure you are required to invoke NSURLConnectionDelegate methods
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.responseData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSString* responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
connection = nil;
}
Related
I have tried this methods, I want to know about integration of rest API in iOS.
I want to know about JSON parsing in web services. I know about these methods but how to use it? but what is function of each method?
This IBAction method sends request string for signup to the server .
-(void)genSignup
{
responseData = [NSMutableData data];
urlLoc= [urlLoc stringByAppendingString:service];
NSLog(#"%#",requestString);
NSData *postData = [requestString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlLoc]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//NSLog(#"%#",request);
PostConnectionRegisterGenUser = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[MyClass removePregressIndicator:self.view];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[MyClass removePregressIndicator:self.view];
if (connection == PostConnectionRegisterGenUser)
{
NSError *error;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"%#",results);
}
}
how to use it?
NSURLConnection is deprecated effective Mac OS 10.11 and iOS 9. So, at this point NSURLSession should be used instead of NSURLConnection.
I just add NSURLSession in your code. Change Key, URL accordingly. I did not compile it.
NSString * requestString = [NSString stringWithFormat:#"Name=%#&Email=%#&Password=%#&MobileNumber=%#&BloodGroup=%#&DeviceID=%#&City=%#&DeviceType=I",txtName.text,txtEmail.text,txtPassword.text,txtMobileno.text,strBlood,strDeviceID,txtCity.text];
NSData *postData = [requestString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlLoc]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = #{ #"api-key": #"API_KEY"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURLSessionDataTask *sessionPostDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// The server answers with an error because it doesn't receive the params
}];
[sessionPostDataTask resume];
Do let me know if you need any other information.
Hope this will help you !!!
Use simple common methods for NSURLSession WS Calling.
-(void)callWebserviceWithParams:(NSDictionary *)aParams withURL:(NSString *)aStrURL withTarget:(UIViewController *)aVCObj withCompletionBlock:(void(^)(NSMutableDictionary *aMutDict))completionBlock withFailureBlock:(void(^)(NSError *error))failure
{
NSString *aStrParams = [self getFormDataStringWithDictParams:aParams];
NSData *aData = [aStrParams dataUsingEncoding:NSUTF8StringEncoding];
aStrURL = [aStrURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *aRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:aStrURL]];
[aRequest setHTTPMethod:#"POST"];
[aRequest setHTTPBody:aData];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
[aRequest setHTTPBody:aData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:aRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//
if (error ==nil) {
NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"ResponseString:%#",aStr);
NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
aMutDict = [aMutDict dictionaryByReplacingNullsWithBlanks];
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(aMutDict);
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
failure(error);
});
}
}];
[postDataTask resume];
}
-(NSString *)getFormDataStringWithDictParams:(NSDictionary *)aDict
{
NSMutableString *aMutStr = [[NSMutableString alloc]initWithString:#""];
for (NSString *aKey in aDict.allKeys) {
[aMutStr appendFormat:#"%#=%#&",aKey,aDict[aKey]];
}
NSString *aStrParam;
if (aMutStr.length>2) {
aStrParam = [aMutStr substringWithRange:NSMakeRange(0, aMutStr.length-1)];
}
else
aStrParam = #"";
return aStrParam;
}
Use Like This
NSDictionary* param = #{
#"Key1":#"Value1",
#"Key2":#"value2"
};
[self callWebserviceWithParams:param withURL:#"URL String" withTarget:self withCompletionBlock:^(NSMutableDictionary *aMutDict) {
//code For Success
} withFailureBlock:^(NSError *error) {
// code for WS Responce failure
}];
also you have to set this method in NSObject Class and make it simple and used in whole app.
Another option Nsurlsession:
-(void)Fetchdata
{
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
// Setup the request with URL
NSURL *url = [NSURL URLWithString:#"http://52.2/category_list.php"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = #"admin_id=19";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];
// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",results);
arryTempdata = [[results valueForKey:#"message"] valueForKey:#"banner"];
NSLog(#"%#",arryTempdata);
tblV.reloadData;
}];
// Fire the request
[dataTask resume];
}
Actually I am using now JSON classes for calling web-services but now i want to call that webservice using NSURLConnection any one provide me code for that.
Please provide me details of frameworks what i have to import.
Thank you in advance.
NSURL *url = [NSURL URLWithString:stringurl];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",dictionary);
}];
You Can use this.
You can Do like this using Synchronous :
NSURL *url=[NSURL URLWithString:urlString];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
NSData *data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSString *response=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dd=[response JSONValue];
OR Using Delegate Method
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSURLResponse *response = nil;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
// NSArray* latestLoans = [json objectForKey:#"loans"];
NSLog(#"json: %#", json);
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
Use below code forrcalling SOAP web service (POST) :
-(NSString *)posturl:(NSString *)url withpoststring:(NSString *)postString {
NSString *post = postString;
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *URL = url;
NSLog(#"%#", URL);
NSLog(#"%#",post);
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
if ([data isEqualToString:#""]) {
} else {
data = stringByStrippingHTML(data);
}
return data;
}
I am fetching data using POST method. And I have successfully retrieved all the data.It's taking too long to display it in UI but I can print it immediately on console, my code is
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.xxxyyy.com/v1/api/client/authorize"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"ABCD" forHTTPHeaderField:#"Authkey"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Authkey"];
NSData* data1 = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
jsonReturnArray = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingAllowFragments error:&error];
NSArray *array = [jsonReturnArray copy];
[self rec:array];
NSString *phoneNumber=[NSString stringWithFormat:#"%#",[jsonReturnArray valueForKey:#"phone"]];
lblPhoneNumber.text = phoneNumber;
NSString *Address=[NSString stringWithFormat:#"%# %# %#,CA %#",[jsonReturnArray valueForKey:#"street1"],[jsonReturnArray valueForKey:#"street2"],[jsonReturnArray valueForKey:#"city"],[jsonReturnArray valueForKey:#"postalcode"]];
lblAddress.text=Address;//takes long time to display
NSLog(#"%#",Address);//immeaditely print
strlatitude=[jsonReturnArray valueForKey:#"latitude"];
strlongitude=[jsonReturnArray valueForKey:#"longitude"];
[self Map:(MKMapView *)mapLocation didUpdateUserLocation:(MKUserLocation *)nil];//method call
}] resume];
This is take too time to print data, but if you use NSURLConnection class it may be help you.This is my Class method it may be helpful.
+ (void)postRequestData:(NSDictionary *)postVars
Action:(APIMode)action
WithCompletionHandlar:(void (^) (id result, BOOL status))completionBlock
{
NSURL *url = [NSURL URLWithString:API_URL([self getAPINameForType:action])];
NSLog(#"Request URL %#",[NSString stringWithFormat:#"%#",url]);
NSString *contentType = #"application/json";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSError *err = nil;
NSMutableDictionary *params=[[NSMutableDictionary alloc] initWithDictionary:postVars];
// [params setObject:[self getAPINameForType:action] forKey:#"mode"];
NSLog(#"Paramater %#",params);
NSData *body = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&err];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%lu", (unsigned long)body.length] forHTTPHeaderField: #"Content-Length"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if(!connectionError)
{
NSError *error = nil;
NSDictionary *dictResponse = [NSDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments error:&error]];
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(dictResponse,(error == nil));
});
NSLog(#"%#",dictResponse);
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(connectionError.localizedDescription,NO);
});
}
}];
}
Use this method instead of it.It is executed fast because NSURLConnection Class execute in background.
Try to fetch your data using NSURLConnection class(manual code) or simply use AFNetworking class(less code). AFNetworking internally uses NSURLConnection class itself.
-(void)showData {
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts"];
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"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"1", #"number",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) {
if(error == nil)
{
NSString *text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
NSLog(#"data is %#", data );
NSLog(#"response is %#" , response);
}];
[postDataTask resume];
}
when i execute the code the debugger jumps from the NSURLSessionDataTask and log generated is __NSCFLocalDataTask: 0x7ff061751960>{ taskIdentifier: 1 } { suspended } and does not come any data in NSData and NSResponse.
#interface UrClass:NsObject<NSURLConnectionDelegate>{ NSMutableData *_receivedData;
}
-(void)showData{
NSString * urlStr = [NSString stringWithFormat:#"%#", path];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
[theRequest setURL:[NSURL URLWithString:urlStr]];
NSString *requestStr = [dictionary JSONRepresentation];
NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", (unsigned int)[requestData length]];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:requestData];
[theRequest addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setTimeoutInterval:REQUEST_TIME_OUT_SECS];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:NO];
[theConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
[theConnection start];
if (theConnection)
_receivedData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
Try this code:
NSURL *url=[NSURL URLWithString:#"https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts"];
NSData *contactData=[NSData dataWithContentsOfURL:url];
NSMutableArray *allContectData=[NSJSONSerialization JSONObjectWithData:contactData options:0 error:nil];
NSLog(#"%#",allContectData);
Otherwise use this code
-(void)showData{
NSString *urlString = #"https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NO timeoutInterval:20.0f];
responseData = [[NSMutableData alloc] init];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
use NSURLConnectionDataDelegate Delegate Method
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSMutableArray *allContectData=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",allContectData);
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"%#",error);
}
I am making a synchronous call to the web service and sometimes I get the correct result back from the web service and sometimes I get HTML result indicating a Runtime error. Is there anything on the iOS side I have to do to correctly call the web service. Here is my code:
NSURLResponse *response = nil;
NSError *error = nil;
NSString *requestString = #"some parameters!";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
NSString *responseData = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
Is it because I am not releasing properly?
you have to set the delegate methods of urlconnection like this
NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
[urlRequest setHTTPMethod:#"POST"];
urLConnection=[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
and the following delegate methods do the trick
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
[receivedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
you will receive error in the following delegate if connection fails
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{}
you better get the response from the finished connection which tells that all the data been received
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
recievedData //the complete data
}
try this
NSError * error;
NSURLResponse * urlresponse;
NSURL * posturl=[NSURL URLWithString:#"Type your webService URL here"];
NSMutableURLRequest * request=[[NSMutableURLRequest alloc]initWithURL:posturl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:50];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSString * body=[NSString stringWithFormat:#"fbid=%#",userid];
[request setHTTPBody:[body dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
NSData * data=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlresponse error:&error];
if (data==nil) {
return;
}
id jsonResponse=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#" json response %#", jsonResponse);
if (![[jsonResponse objectForKey:#"code"] isEqualToNumber:[NSNumber numberWithInt:200]]) {
NSLog( #" successFull ");
this method works for me for more information read facebook documents for ios login
//set request
NSURLRequest *req=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://indianbloodbank.com/api/donors/?bloodgroup=O%2B"]];
NSLog(#"Request-%#",req);
NSError *err=nil;
NSURLResponse *res=nil;
NSData *xmldata=[NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&err];
NSLog(#"Error-%#",err);
NSLog(#"Response-%#",res);
NSLog(#"XmlData-%#",xmldata);
xmldictionary=[XMLReader dictionaryForXMLData:xmldata error:&err];
NSLog(#"XmlDictionary-%#",xmldictionary);
mArray=[xmldictionary retrieveForPath:#"response.donorslist.donors"];
NSLog(#"MutableArray-%#",mArray);
lblname.text=[[mArray objectAtIndex:0]valueForKey:#"name"];
lbllocation.text=[[mArray objectAtIndex:0]valueForKey:#"location"];
lblphone.text=[[mArray objectAtIndex:0]valueForKey:#"phone"];
NSLog(#"%#,%#,%#",lblname.text,lbllocation.text,lblphone.text);
NSLog(#"%#",mArray);
For loop:
for (int i=0; i<mArray.count; i++)
{
Data * don=[NSEntityDescription insertNewObjectForEntityForName:#"Data" inManagedObjectContext:app.managedObjectContext];
don.donorid=[[mArray objectAtIndex:i]valueForKey:#"id"];
don.gender=[[mArray objectAtIndex:i]valueForKey:#"gender"];
don.name=[[mArray objectAtIndex:i]valueForKey:#"name"];
don.location=[[mArray objectAtIndex:i]valueForKey:#"location"];
don.phone=[[mArray objectAtIndex:i]valueForKey:#"phone"];
[app saveContext];
NSLog(#"%#,%#,%#,%#,%#",[[mArray objectAtIndex:i]valueForKey:#"id"],[[mArray objectAtIndex:i]valueForKey:#"gender"],[[mArray objectAtIndex:i]valueForKey:#"name"],[[mArray objectAtIndex:i]valueForKey:#"location"],[[mArray objectAtIndex:i]valueForKey:#"phone"]);
}