I am beginner in IOS programming. My question is my app fetching data from JSON in my web server, when starting the apps, it is slightly lag and delay due to the fetching process, so i would like to show activity indicator when i connecting to JSON data. How can i do that?
My JSON coding:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *urlAddress = [NSURL URLWithString:#"http://emercallsys.webege.com/RedBoxApp/getEvents.php"];
NSStringEncoding *encoding = NULL;
NSError *error;
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:&error];
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
eventsDetail = [[dict objectForKey:#"eventsDetail"] retain];
}
[jsonreturn release];
}
use the following code
//add a UIActivityIndicatorView to your nib file and add an outlet to it
[indicator startAnimating];
indicator.hidesWhenStopped = YES;
dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
//Load the json on another thread
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:NULL];
[jsonreturn release];
//When json is loaded stop the indicator
[indicator performSelectorOnMainThread:#selector(stopAnimating) withObject:nil waitUntilDone:YES];
});
You can use something like below code:
- (void)fetchData
{
[activityIndicator startAnimating];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *theRequest = [[NSURLRequest alloc]initWithURL:url];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection) {
}
else {
NSLog(#"The Connection is NULL");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
webData = [[NSMutableData data] retain];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction %#",error);
UIAlertView *connectionAlert = [[UIAlertView alloc] initWithTitle:#"Information !" message:#"Internet / Service Connection Error" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[connectionAlert show];
[connectionAlert release];
[connection release];
[webData release];
return;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
//NSLog(#"Received data :%#",theXML);
//[theXML release];
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary: webData error:&error];
if (dict) {
eventsDetail = [[dict objectForKey:#"eventsDetail"] retain];
}
[activityIndicator stopAnimating];
}
Related
hi i am giving reference link of stack over flow
How to update Google Maps marker position in swift/iOS
You can try the online swift to objective c converters. Like
http://objc2swift.me
These converts are used to convert objective c to Swift. I know you want to convert Swift to objective C. But I think you can learn some think to here. Just write the code. Swift is very similar to objective c.Only difference in syntax. You can understand very easily.
*Stack Overflow not for Writing Codes. If you have any Problem in codes. We will help you.
Here is the code, Create a button, add selector to that button. Hope you will set your google map.
NSMutableData *webData;
#property NSURLConnection *connection;
-(void) getResult //call this in button selector
{
marker=nil; //create a GMSMarker globally.
[self.mapView clear];
NSString *strUrl = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%#&type=atm&sensor=true&name=%#&key=%#",latitude,longitude,_radius.text,_searchTxt.text,googleAPI_Key ];
[self addMarkerDataUrl:strUrl];
}
-(void)addMarkerDataUrl:(NSString *)urlString
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString* urlTextEscaped = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlTextEscaped]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
[request setHTTPMethod: #"GET"];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(self.connection)
{
webData = [[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (webData)
{
[self gettingData:webData ];
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
webData=nil;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#" response %d",kCFURLErrorNotConnectedToInternet);
if ([error code] == kCFURLErrorNotConnectedToInternet)
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:#"No Connection Error"
forKey:NSLocalizedDescriptionKey];
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:userInfo];
NSLog(#"error %#",noConnectionError);
[self handleError:noConnectionError];
}
else
{
[self handleError:error];
}
self.connection = nil;
[self errorInConnection];
}
- (void)handleError:(NSError *)error
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"SUBCOMMUNE" message:#"Timed Out" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
-(void)errorInConnection
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Try again after some time" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
- (void) gettingData:(NSData *)data
{
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray* places = [json objectForKey:#"results"];
NSLog(#"Google Data: %#", places);
tempArray = [[NSMutableArray alloc]init];
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if([[NSString stringWithFormat:#"%#",[allDataDictionary objectForKey:#"status"]]isEqualToString:#"OK"])
{
collectionArray =[[NSMutableArray alloc]init];
locArray = [[NSMutableArray alloc]init];
NSMutableArray *legsArray = [[NSMutableArray alloc] initWithArray:allDataDictionary[#"results"]];
for (int i=0; i< [legsArray count]; i++)
{
[collectionArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:legsArray[i][#"icon"],#"icon", legsArray[i][#"name"],#"name",legsArray [i][#"vicinity"],#"vicinity",legsArray[i][#"id"],#"id",nil]];
[locArray addObject:legsArray[i][#"geometry"][#"location"]];
[tempArray addObject:legsArray[i][#"vicinity"]];
}
NSLog(#"CollectionArray =%#",collectionArray);
NSLog(#"LocationArray =%lu",(unsigned long)locArray.count);
[self addMarkers];
}
else
{
NSString *msg=[allDataDictionary objectForKey:#"error_message"];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Error !\n Check Radius or ATM Name" message:msg delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
-(void)addMarkers
{
for(int i=0;i<locArray.count;i++)
{
starting = [NSMutableDictionary dictionaryWithObjectsAndKeys:locArray[i][#"lat"],#"lat",locArray[i][#"lng"],#"lng", nil];
name = [NSMutableDictionary dictionaryWithObjectsAndKeys:collectionArray[i][#"name"],#"name",nil];
CLLocationCoordinate2D position = CLLocationCoordinate2DMake([[starting objectForKey:#"lat"] doubleValue] , [[starting objectForKey:#"lng"] doubleValue]);
marker1 = [GMSMarker markerWithPosition:position];
GMSCameraUpdate *updatedCamera=[GMSCameraUpdate setTarget:CLLocationCoordinate2DMake(latitude, longitude) zoom:15];
[self.mapView animateWithCameraUpdate:updatedCamera];
marker1.title = [name objectForKey:#"name"];
[marker1 setIcon:[UIImage imageNamed:#"Map Pin-48.png"]];
marker1.appearAnimation = YES;
marker1.map = self.mapView;
}
}
I am working on a web service app and i have a question. I am calling a specific Url site with the following code:
NSURL *Url = [NSURL URLWithString:[requestStream stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *htmlString = [NSString stringWithContentsOfURL:Url encoding:NSUTF8StringEncoding error:&error];
Then i create an nsstring and print it with the NSLog and i got the following results:
2014-05-14 15:50:58.118 jsonTest[1541:907] Data : Array
(
[url] => http://sheetmusicdb.net:8000/hnInKleinenGruppen
[encoding] => MP3
[callsign] => SheetMusicDB.net - J
[websiteurl] =>
)
My question in how can i parse the URL link and then use it as a value? I tried to put them to an array or a dictionary but i get error back. So if anyone can help me i would appreciate it.
Ok i managed to grab the link with the following code:
if(htmlString) {
//NSLog(#"HTML %#", htmlString);
NSRange r = [htmlString rangeOfString:#"=>"];
if (r.location != NSNotFound) {
NSRange r1 = [htmlString rangeOfString:#"[encoding]"];
if (r1.location != NSNotFound) {
if (r1.location > r.location) {
_streamTitle = [htmlString substringWithRange:NSMakeRange(NSMaxRange(r), r1.location - NSMaxRange(r))];
NSLog(#"Title %#", _streamTitle);
}
}
}
} else {
NSLog(#"Error %#", error);
}
Thank you for your suggestions. My problem now is that i pass the string into an avplayer and i can't hear music.
I think this will be help for you..
// #property (nonatomic,retain) NSMutableData *responseData;
// #synthesize responseData;
NSString *urlString=#"http:your urls";
self.responseData=[NSMutableData data];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self];
NSLog(#"connection====%#",connection);
JSON Delegates :
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
self.responseData=nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray *response_Array = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];
// Write code for retrieve data according to your Key.
}
Try This:
NSString *urlStr=[NSString stringWithFormat:#"uRL"];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
if (theConnection)
{
receivedData=[[NSMutableData data] retain] ;
}
#pragma mark - Connection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// append the new data to the receivedData
// receivedData is declared as a method instance elsewhere
//NSLog(#"data %#",data);
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// release the connection, and the data object
// [connection release];
// [receivedData release];
UIAlertView *prompt = [[UIAlertView alloc] initWithTitle:#"Connection Failed" message:[error localizedDescription]delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[prompt show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *content = [[NSString alloc] initWithBytes:[receivedData bytes]
length:[receivedData length] encoding: NSUTF8StringEncoding];
NSData *jsonData = [content dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
}
I am using the Yelp Search API to basically just get a list of businesses for a search query.
It is pretty much a NSURLConnection is OAuth, but here is the code to initialize the request:
NSURL *URL = [NSURL URLWithString:appDelegate.yelpAdvancedURLString];
OAConsumer *consumer = [[OAConsumer alloc] initWithKey:#"this-is-my-key" secret:#"this-is-my-secret"];
OAToken *token = [[OAToken alloc] initWithKey:#"this-is-my-key" secret:#"this-is-my-secret"];
id<OASignatureProviding, NSObject> provider = [[OAHMAC_SHA1SignatureProvider alloc] init];
NSString *realm = nil;
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:URL
consumer:consumer
token:token
realm:realm
signatureProvider:provider];
[request prepare];
responseData = [[NSMutableData alloc] init];
yelpConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Then here:
- (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 {
NSLog(#"Error: %#, %#", [error localizedDescription], [error localizedFailureReason]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Oops." message: #"Something screwed up. Please search again." delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connection == self.yelpConnection) {
[self setYelpString];
}
}
When I run this on iPhone, everything is working fine. However, when I run on iPad, the connection gets timed out. The following is from this line
NSLog(#"Error: %#, %#", [error localizedDescription], [error localizedFailureReason]);
Error: The request timed out., (null)
Also if I use a synchronous request, it seems to work using this:
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary* JSON = [NSJSONSerialization
JSONObjectWithData:result
options:kNilOptions
error:&error];
However, I want to avoid using synchronous as it freezes the app.
Is this Yelp API specific? Or am I just doing something wrong? Thanks in advance, I would appreciate any help.
If it helps, it times out approximately 10 seconds after sending the request.
create this type of NSMutableURLRequest :
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:240.0];
I think the best approach is to change the init method in http://oauth.googlecode.com from
- (id)initWithURL:(NSURL *)aUrl
consumer:(OAConsumer *)aConsumer
token:(OAToken *)aToken
realm:(NSString *)aRealm
signatureProvider:(id<OASignatureProviding, NSObject>)aProvider
{
if (self = [super initWithURL:aUrl
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10.0])
{
...
}
}
to
- (id)initWithURL:(NSURL *)aUrl
cachePolicy:(NSURLRequestCachePolicy)cachePolicy
timeoutInterval:(NSTimeInterval)timeoutInterval
consumer:(OAConsumer *)aConsumer
token:(OAToken *)aToken
realm:(NSString *)aRealm
signatureProvider:(id<OASignatureProviding, NSObject>)aProvider
{
if (self = [super initWithURL:aUrl
cachePolicy:cachePolicy
timeoutInterval:timeoutInterval])
{
...
}
and then check again, whether the timeout value which you specify will be honored by the connection.
Hey guyz I have this issue regarding the NSUrlConnection where I initiate a request like this
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:URL_PACKAGE,2]]];
Communication *comm = [[Communication alloc] initWithUrlRequest:request];
comm.request_name = request_name;
comm.delegate = self;
[comm startAsynchronous];
[request release];
and then the response getting code is fine but as you can see I have created a communication class to make the connection and when I request with difference web services it
- (Communication *) initWithUrlRequest:(NSMutableURLRequest *)url_request {
self.request = url_request;
return self;
}
-(void)dealloc {
[super dealloc];
}
- (void) startAsynchronous {
responseData = [[NSMutableData data] retain];
NSLog(#"%#",[request URL]);
downloadConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
[responseData setLength:0];
if ( [[self delegate] respondsToSelector:#selector(communication:didReceiveResponse:RequestName:)] ) {
[self.delegate communication:self didReceiveResponse:response RequestName:self.request_name];
}
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
[responseData appendData:data];
if ( [[self delegate] respondsToSelector:#selector(communication:didReceiveData:RequestName:)] ) {
[self.delegate communication:self didReceiveData:data RequestName:self.request_name];
}
}
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error {
[self.delegate communication:self didFailWithError:error RequestName:self.request_name];
NSLog(#"%#", error);
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection {
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
[responseData release];
responseString = [responseString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
responseString = [responseString stringByReplacingOccurrencesOfString:#"+" withString:#" "];
responseString = [responseString stringByReplacingOccurrencesOfString:#"null" withString:#"\"\""];
[self.delegate communication:self didFinishWithString:responseString RequestName:self.request_name];
}
The error is
2013-07-30 13:55:46.994 Ipad Qld[3982:c07] *** -[Requests respondsToSelector:]: message sent to deallocated instance 0xa16b310
I want to use json in my application. I can parse json from url with this code :
#import "ViewController.h"
#implementation ViewController
{
NSDictionary *titles;
NSMutableData *Data;
NSArray *fileContent;
NSArray *folderContent;
NSMutableArray *all;
}
#synthesize Table;
- (void)viewDidLoad
{
[super viewDidLoad];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url =[NSURL URLWithString:#"http://192.168.1.100/veis/root/developers/api/filemanager.php?key=5147379269&getlist=root"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
Data = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[Data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
titles = [NSJSONSerialization JSONObjectWithData:Data options:kNilOptions error:nil];
fileContent = [titles objectForKey:#"fileContent"];
folderContent = [titles objectForKey:#"folderContent"];
all = [[NSMutableArray alloc]init];
[all addObjectsFromArray:folderContent];
[all addObjectsFromArray:fileContent];
[Table reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"The Connection has been LOST" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
but I want when I dont have internet I can to use of json. I dont know how to use of json in way offline (or local in my device)
can you guide me in this issue that how to use json in way offline
The way parsing should be same for Online and Offline json data, both are same, just you need to write a file using Unparsed data say data.json in Documents Directory, if you want to use the same process to use json, but if you want to use parsed json, then write it as plist..
You can try to use the following methods
-(void)saveJsonWithData:(NSData *)data{
NSString *jsonPath=[[NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:#"/data.json"];
[data writeToFile:jsonPath atomically:YES];
}
-(NSData *)getSavedJsonData{
NSString *jsonPath=[[NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:#"/data.json"];
return [NSData dataWithContentsOfFile:jsonPath]
}
Then call the function as
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self saveJsonWithData:data];
}