I am Getting EXC_BAD_ACCESS while NSURLREQUEST - iphone

I am getting EXC_BAD_ACCESS while NSURLREQUEST.
I am giving pdf url from server to to webview through AppDelegate_iPhone's currentBookPressed.
please can anyone tell what is the problem ...
Code:-
#class AppDelegate_iPhone;
#interface PdfShowViewController : UIViewController<UIWebViewDelegate> {
UIWebView *pdfWebview;
AppDelegate_iPhone *appDelegate;
NSMutableData *receivedData;
UIActivityIndicatorView *myIndicator;
IBOutlet UIProgressView *progress;
NSURLRequest* DownloadRequest;
NSURLConnection* DownloadConnection;
long long bytesReceived;
long long expectedBytes;
}
#property (nonatomic,retain) UIWebView *pdfWebview;
#property (nonatomic,retain) UIActivityIndicatorView *myIndicator;
#property (nonatomic,retain) IBOutlet UIProgressView *progress;
#property (nonatomic,retain) NSMutableData *receivedData;
#property (nonatomic, readonly, retain) NSURLRequest* DownloadRequest;
#property (nonatomic, readonly, retain) NSURLConnection* DownloadConnection;
-(IBAction)onTapBack;
#end
#import "PdfShowViewController.h"
#import "AppDelegate_iPhone.h"
#implementation PdfShowViewController
#synthesize pdfWebview,myIndicator,progress,receivedData,DownloadRequest,DownloadConnection;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
unsigned char byteBuffer[[receivedData length]];
[receivedData getBytes:byteBuffer];
NSLog(#"Data === %ld",receivedData);
NSInteger receivedLen = [data length];
bytesReceived = (bytesReceived + receivedLen);
NSLog(#"received Bytes == %f",bytesReceived);
if(expectedBytes != NSURLResponseUnknownLength)
{
NSLog(#"Expected Bytes in if == %f",expectedBytes);
NSLog(#"received Bytes in if == %f",bytesReceived);
float value = ((float) (bytesReceived *100/expectedBytes))/100;
NSLog(#"Value == %f",value);
progress.progress=value;
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//[connection release];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
expectedBytes = [response expectedContentLength];
NSLog(#"%f",expectedBytes);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[myIndicator stopAnimating];
[myIndicator removeFromSuperview];
pdfWebview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 40, 320, 420)];
[pdfWebview setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
[pdfWebview setScalesPageToFit:YES];
[pdfWebview setAutoresizesSubviews:YES];
[pdfWebview loadRequest:DownloadRequest];
[self.view addSubview:pdfWebview];
//[connection release];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];
myIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
myIndicator.center = self.view.center;
myIndicator.hidesWhenStopped = NO;
[self.view addSubview:myIndicator];
[myIndicator startAnimating];
//receivedData = [[NSMutableData alloc] initWithLength:0];
NSLog(#"%#",appDelegate.currentBookPressed);
NSString * urlString = [appDelegate.currentBookPressed stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSLog(#"%#",urlString);
NSURL *targetURL = [NSURL URLWithString:urlString];
NSLog(#"%#",targetURL);
// Here comes Acception
DownloadRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:targetURL] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:120.0];
DownloadConnection = [[NSURLConnection alloc] initWithRequest:DownloadRequest delegate:self];
if (DownloadConnection) {
receivedData = [[[NSMutableData data]initWithLength:0]retain];
}
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
-(IBAction)onTapBack
{
[self dismissModalViewControllerAnimated:YES];
}
- (void)dealloc {
[super dealloc];
[pdfWebview release];
[receivedData release];
}
#end

You should replace line
DownloadRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:targetURL] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:120.0];
with line
DownloadRequest = [NSURLRequest requestWithURL:targetURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:120.0];
It is because method requestWithURL:cachePolicy:timeoutInterval: in first parameter is waiting for object of NSURL class. In targerURL you have exactly that one.
Moreover in method [NSURL URLWithString:targetURL] (if you will need it) you should pass NSString as a first parameter, but you are passing NSURL.

Your problem in this line
DownloadRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:targetURL] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:120.0];
The problem in your case arises because parameter for + (id)URLWithString:(NSString *)URLString is NSString and you are passing NSURL and method trying to get the length of the supposed string by calling -length, which exists for NSString but not for NSURL.

Related

All output Results are working but tableview is not load data from web service in iphone

I want load data to tableview from my web service in my iphone application. All outputs are working correctly but my table doesn't contain any data. It is empty.
I did not find any mistake in the application. Why doesn't the tableview load data from the web service ?
ScoreClass.h
#interface ScoreClass : NSObject {
IBOutlet NSInteger *ScoreID;
IBOutlet NSInteger *UserScore;
IBOutlet NSInteger *GameID;
IBOutlet NSString *MacID;
IBOutlet NSString *NickName;
IBOutlet Boolean *IsDeleted;
IBOutlet NSDate *CreatedOn;
IBOutlet NSDate *ModifiedOn;
NSMutableArray *ScoreList;
}
#property(assign, readwrite) NSInteger *ScoreID;
#property(assign, readwrite) NSInteger *UserScore;
#property(assign, readwrite) NSInteger *GameID;
#property(nonatomic, retain) NSString *MacID;
#property(nonatomic, retain) NSString *NickName;
#property(nonatomic, assign) Boolean *IsDeleted;
#property(nonatomic, retain) NSDate *CreatedOn;
#property(nonatomic, retain) NSDate *ModifiedOn;
#property(retain, readwrite) NSMutableArray *ScoreList;
#end
ScoreClass.m
#import "ScoreClass.h"
#implementation ScoreClass
#synthesize ScoreID, UserScore, GameID, MacID, NickName, IsDeleted,CreatedOn, ModifiedOn,ScoreList;
-(id)init {
[super init];
MacID = [NSString stringWithFormat:#""];
NickName= [NSString stringWithFormat:#""];
return self;
}
-(void) dealloc{
[MacID release];
[NickName release];
[super dealloc];
}
#end
ScoreWebService.h
#import <UIKit/UIKit.h>
#import "ScoreClass.h"
#interface ScoreWebService : UIViewController {
// Request
NSString *address;
NSString *xmlNamespace;
NSString *operation;
NSString *parameters;
NSMutableString *inComeValue;
// Connection
BOOL recordResults;
BOOL connectionFinished;
// Xml Parsing
NSMutableString *soapResults;
NSMutableData *webData;
NSXMLParser *xmlParser;
ScoreClass *score;
NSMutableArray *ScoreList;
}
#property(nonatomic, retain) NSString *address;
#property(nonatomic, retain) NSString *xmlNamespace;
#property(nonatomic, retain) NSString *operation;
#property(nonatomic, retain) NSString *parameters;
#property(nonatomic, retain) NSMutableString *inComeValue;
#property(retain, readwrite) NSMutableArray *ScoreList;
#property(nonatomic, retain) ScoreClass *score;
#end
ScoreWebService.m
#import "ScoreWebService.h"
#implementation ScoreWebService
#synthesize operation, parameters, address, xmlNamespace, inComeValue, score;
#synthesize ScoreList;
-(id)init {
[super init];
address = [NSString stringWithFormat:#""];
xmlNamespace = [NSString stringWithFormat:#""];
operation = [NSString stringWithFormat:#""];
parameters = [NSString stringWithFormat:#""];
inComeValue = [NSString stringWithFormat:#""];
score = [[ScoreClass alloc]init];
ScoreList = [[NSMutableArray alloc]init];
return self;
}
-(NSMutableArray *)ScoreTableWebService{
if (([address isEqualToString:#""]) || ([xmlNamespace isEqualToString:#""]) || ([operation isEqualToString:#""])) {
//return;
}
recordResults = FALSE;
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<BayiSatisTakipTablo6Oku xmlns=\"http://trigonservis.com/\">"
"<IstasyonKodu>34005</IstasyonKodu>"
"<Gun1>02.01.2012</Gun1>"
"</BayiSatisTakipTablo6Oku>"
"</soap:Body>"
"</soap:Envelope>"
];
NSLog(#"Request SOAP = \n%#\n\n", soapMessage);
NSURL *url = [NSURL URLWithString:address];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://trigonservis.com/BayiSatisTakipTablo6Oku" forHTTPHeaderField:#"SOAPAction"];
  [theRequest addValue: soapMessage forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
//Connexion
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection ) {
webData = [[NSMutableData data] retain];
}
else {
NSLog(#"there is a problem to connect webservices");
}
while (!connectionFinished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
return ScoreList;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
#if(TARGET_IPHONE_SIMULATOR)
NSLog(#"Reponse SOAP = \n%#\n\n", theXML);
#endif
[theXML release];
// Appel futur du parser
if(xmlParser)
[xmlParser release];
// Allocation du NSXMLParser
xmlParser = [[NSXMLParser alloc] initWithData: webData];
// Désigne l'instance de la classe courante comme étant le delegate du NSXMLParser
[xmlParser setDelegate: self];
[xmlParser setShouldResolveExternalEntities: YES];
[xmlParser parse];
[connection release];
[webData release];
connectionFinished = TRUE;
}
/************************************************************************************
** Connection */
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
[webData release];
}
/************************************************************************************
** XML Parsing
*/
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict {
NSLog(#"elementName = %# \n", elementName);
if( [elementName isEqualToString:#"DagiticiSatis"])
{
if(!soapResults)
soapResults = [[NSMutableString alloc] init];
recordResults = TRUE;
}
else if( [elementName isEqualToString:#"IstasyonAdi"])
{
if(!soapResults)
soapResults = [[NSMutableString alloc] init];
recordResults = TRUE;
}
return;
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if( recordResults ){
[soapResults appendString: string];
}
}
-(NSMutableArray *)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if( [elementName isEqualToString:#"DagiticiSatis"]) {
#if(TARGET_IPHONE_SIMULATOR)
NSLog(#"ScoreID = %# \n", soapResults);
#endif
score = [[ScoreClass alloc]init];
score.MacID = soapResults;
[soapResults release];
soapResults = nil;
}
else if( [elementName isEqualToString:#"IstasyonAdi"]){
#if(TARGET_IPHONE_SIMULATOR)
NSLog(#"IstasyonAdi = %# \n", soapResults);
#endif
score.NickName = soapResults;
[soapResults release];
soapResults = nil;
}
return ScoreList;
}
#end
GridTableViewCell.h
#import <UIKit/UIKit.h>
#interface GridTableViewCell : UITableViewCell {
UIColor *lineColor;
BOOL topCell;
UILabel *cell1;
UILabel *cell2;
UILabel *cell3;
}
#property (nonatomic, retain) UIColor* lineColor;
#property (nonatomic) BOOL topCell;
#property (readonly) UILabel* cell1;
#property (readonly) UILabel* cell2;
#property (readonly) UILabel* cell3;
#end
GridTableViewCell.m
#import "GridTableViewCell.h"
#define cell1Width 80
#define cell2Width 80
#define cellHeight 44
#implementation GridTableViewCell
#synthesize lineColor, topCell, cell1, cell2, cell3;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
topCell = NO;
// Add labels for the three cells
cell1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, cell1Width, cellHeight)];
cell1.textAlignment = UITextAlignmentCenter;
cell1.backgroundColor = [UIColor clearColor]; // Important to set or lines will not appear
[self addSubview:cell1];
cell2 = [[UILabel alloc] initWithFrame:CGRectMake(cell1Width, 0, cell2Width, cellHeight)];
cell2.textAlignment = UITextAlignmentCenter;
cell2.backgroundColor = [UIColor clearColor]; // Important to set or lines will not appear
[self addSubview:cell2];
cell3 = [[UILabel alloc] initWithFrame:CGRectMake(cell1Width+cell2Width, 0, 320-(cell1Width+cell2Width), cellHeight)]; // Note - hardcoded 320 is not ideal; this can be done better
cell3.textAlignment = UITextAlignmentCenter;
cell3.backgroundColor = [UIColor clearColor]; // Important to set or lines will not appear
[self addSubview:cell3];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)dealloc
{
[cell1 release];
[cell2 release];
[cell3 release];
[super dealloc];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, lineColor.CGColor);
// CGContextSetLineWidth: The default line width is 1 unit. When stroked, the line straddles the path, with half of the total width on either side.
// Therefore, a 1 pixel vertical line will not draw crisply unless it is offest by 0.5. This problem does not seem to affect horizontal lines.
CGContextSetLineWidth(context, 1.0);
// Add the vertical lines
CGContextMoveToPoint(context, cell1Width+0.5, 0);
CGContextAddLineToPoint(context, cell1Width+0.5, rect.size.height);
CGContextMoveToPoint(context, cell1Width+cell2Width+0.5, 0);
CGContextAddLineToPoint(context, cell1Width+cell2Width+0.5, rect.size.height);
// Add bottom line
CGContextMoveToPoint(context, 0, rect.size.height);
CGContextAddLineToPoint(context, rect.size.width, rect.size.height-0.5);
// If this is the topmost cell in the table, draw the line on top
if (topCell)
{
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, rect.size.width, 0);
}
// Draw the lines
CGContextStrokePath(context);
}
- (void)setTopCell:(BOOL)newTopCell
{
topCell = newTopCell;
[self setNeedsDisplay];
}
#end
1 Set the delegate for table.
2 Assign data from web service to NSMutableArray.
3 Write method mentioned below.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//create cell here
}
4 call
[tblView reloadData];

NSURLConnection very long downloading

I'm facing problem with downloading 5 MB file, it taking more then 2 minutes on iPhone 5 with iOS 6.1.
Using iPhone 4S with same iOS version it taking only 10 seconds, both are using WiFi.
I have tried different cache Policy and timeout Interval of NSURLRequest, it changed nothing, it's still taking long time. Download is over HTTP.
I'm using NSURLConnection class, before downloading this "big" file I'm downloading two others.
Don't know what else can be important,to reduce the time.
Thanks in advance.
Code:
#interface MyClass : NSObject <NSURLConnectionDelegate>
{
#private id delegate;
NSURLConnection *connection;
NSMutableData* responseData;
//...
}
#import "MyClass.h"
#implementation MyClass
-(void)getObj1:(id)delegateObj
{
delegate = delegateObj;
NSString *url = #"...";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:120.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(connection)
{
responseData = [NSMutableData data];
}
}
-(void)getObj2:(*String)somesString
{
NSString *url = #"...";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:120.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(connection)
{
responseData = [NSMutableData data];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//....
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(firstRequest)
{
//save data from first request and set responseData clear
[self getObj2:#"..."];
}
}
and others without anything special, I hope this will be enough
I have found this post https://devforums.apple.com/message/754875#754875 but still doesn't work fine for me. However now I better understand this strange situation.
Use AFDownloadRequestOperation (AFNetworking "sublass") - you can have also pause/resume operation.
Here you have an example https://stackoverflow.com/a/12209618
You used GCD dispatch_async queue to execute set of NSURLRequest request to download data from server or getting server response.
NSString *webURL = #"http://therealurl.appspot.com/?format=json&url=bit.ly/a";
NSURL *url = [NSURL URLWithString:webURL];
NSURLRequest *awesomeRequest = [NSURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:awesomeRequest delegate:self];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
NSRunLoop *loop=[NSRunLoop currentRunLoop];
[connection scheduleInRunLoop:loop forMode:NSRunLoopCommonModes];
//[self processTheAwesomeness];
});
Well in my experience AFNetworking does an awsome job in handling the downloads.I am using a downloading operation on files with 10+ MB size .So I strongly suggest using it.
My answer on stack to show progressbar.See the answer where i implement both the ways ,with AFNetworking and NSUrlconnection.You can try both ways and can see the progress and you can calculate how the bytes get downloaded in each packet.By tracking it so you can analyse how it varies in the download time.
Try it
I'd propose a solution where you have some kind of a communication manager which has an NSOperationQueue it handles, with a single entry point method where you give it a the URL where the content lives you want to download and a success and a failure block.
The communication manager than creates an NSOperation where you create the NSURLRequest and handle the callbacks.
As soon as the commninication manager puts the operation onto the queue its start method is called.
In my communication manager implementation I keep track (besides putting the operations onto the queue) of every started operation via an NSMutableDictionary so that you can cancel a single or all operations (In the sample code provided the operationKey is used for this purpose. Here the JSONOperation returns (in case of success) an NSString to the communicator but it could be any kind of data too, e.g. I use the same class for downloading images, so I'd pass back the data object itself.
Below you can find my JSONOperation class as an example. I you like the idea I could put the other files on Gist.
My NSOperation looks like this
#interface JSONOperation : NSOperation <NSURLConnectionDataDelegate, OperationDelegate>
+ (instancetype)jsonOperationForProvider:(id)provider success:(OperationSuccessWithString)success failure:(OperationFailure)failure;
#end
#import "JSONOperation.h"
#import "ProviderDelegate.h"
#interface JSONOperation()
#property (nonatomic, assign) BOOL executing;
#property (nonatomic, assign) BOOL finished;
#property (nonatomic, assign) BOOL cancelled;
#property (nonatomic, strong) NSURL *url;
#property (nonatomic, weak) id <ProviderDelegate> delegate;
#property (nonatomic, strong) NSURLConnection *connection;
#property (nonatomic, strong) NSMutableData *receivedData;
#property (nonatomic, copy) OperationFailure failure;
#property (nonatomic, copy) OperationSuccessWithString success;
#end
#implementation JSONOperation
- (void)start
{
if ([self isCancelled])
{
[self willChangeValueForKey:#"isFinished"];
_finished = YES;
[self didChangeValueForKey:#"isFinished"];
return;
}
NSURLRequest *request = [NSURLRequest requestWithURL:self.url];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[self.connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
[self.connection start];
[self willChangeValueForKey:#"isExecuting"];
_executing = YES;
[self didChangeValueForKey:#"isExecuting"];
}
- (NSMutableData *)receivedData
{
if (nil == _receivedData) {
_receivedData = [NSMutableData data];
}
return _receivedData;
}
+ (instancetype)jsonOperationForProvider:(id <ProviderDelegate>)provider success:(OperationSuccessWithString)success failure:(OperationFailure)failure
{
NSAssert(nil != provider, #"provider parameter can't be nil");
JSONOperation *operation = [[[self class] alloc] init];
operation.delegate = provider;
operation.url = provider.contentURL;
operation.failure = failure;
operation.success = success;
return operation;
}
- (BOOL)isConcurrent {
return YES;
}
- (BOOL)isExecuting {
return _executing;
}
- (BOOL)isFinished {
return _finished;
}
- (BOOL)isCancelled {
return _cancelled;
}
#pragma mark - NSURLConnectionDataDelegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (_success) {
NSString *receivedText = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
_receivedData = nil;
self.success(self, receivedText);
}
[self willChangeValueForKey:#"isFinished"];
[self willChangeValueForKey:#"isExecuting"];
_executing = NO;
_finished = YES;
[self didChangeValueForKey:#"isExecuting"];
[self didChangeValueForKey:#"isFinished"];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection cancel];
_connection = nil;
_receivedData = nil;
_url = nil;
if (_failure) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.failure(self, error);
}];
}
[self willChangeValueForKey:#"isFinished"];
[self willChangeValueForKey:#"isExecuting"];
_executing = NO;
_finished = YES;
[self didChangeValueForKey:#"isExecuting"];
[self didChangeValueForKey:#"isFinished"];
}
#pragma mark - OperationDelegate
- (NSString *)operationKey
{
return [self.url absoluteString];
}
- (id)provider
{
return _delegate;
}
- (void)cancelOperation
{
_failure = nil;
_success = nil;
[self.connection cancel];
_connection = nil;
_receivedData = nil;
_url = nil;
[self willChangeValueForKey:#"isCancelled"];
[self willChangeValueForKey:#"isFinished"];
[self willChangeValueForKey:#"isExecuting"];
_executing = NO;
_finished = YES;
_cancelled = YES;
[self didChangeValueForKey:#"isCancelled"];
[self didChangeValueForKey:#"isExecuting"];
[self didChangeValueForKey:#"isFinished"];
}
#end
EDIT - Gist Sample files
Have you tried AFNetworking? It' s a wrapper on NSURLConnection. I'm not sure if it would help you in getting a faster download, but it sure does give you an edge over NSURLConnection.
Just try using gzip to compress the remote file for NSURLRequest. It'll speed up your connection dramatically.
To use this, you need to have it installed on the server, and the good news is if you're using apache2 on your server, it comes by default. To test to make sure your server/URL had gzip compression enabled, test it with this online tool:
http://www.feedthebot.com/tools/gzip/
If the answer is yes, proceed to add the code to your Objective-C code in Xcode. After this line in your code:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:120.0];
just add this:
// Create a mutable copy of the immutable request and add more headers
NSMutableURLRequest *mutableRequest = [request mutableCopy];
//add gzip compression
[mutableRequest addValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
// Now set our request variable with an (immutable) copy of the altered request
request = [mutableRequest copy];
This will speed up your response time noticeably, and you do not need to use AFNetworking for a small NSURLRequest or NSURLConnection task.
I'm not sure what your problem is, but the following code works reliably for me.
- (id)init
{
self.downloadQueue = [[NSOperationQueue alloc] init];
[self.downloadQueue setMaxConcurrentOperationCount:1];
}
- (void)doDownload:(NSURL *)url
{
[self.downloadQueue addOperation:[NSBlockOperation blockOperationWithBlock:^{
NSData *data =[NSData dataWithContentsOfURL:url];
dispatch_sync(dispatch_get_main_queue(), ^{
NSAutoreleasePool *mainQueuePool = [[NSAutoreleasePool alloc] init];
... update user interface ...
[mainQueuePool release];
});
}]];
}
I think it's a problem in your device. Try another device from a friend.

Reading JSON from URL and adding MKAnnotations

I've been through several different tutorials trying to get this working, but they seem to gloss over some crucial steps that a beginner might not know.
I have a JSON file at a URL with name, latitude, and longitude listed. How can I import that to an array or dictionary (I don't know the difference), and then iterate over it and create a new annotation with each iteration.
IOS6, Storyboards
_ Added Code _
ViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface ViewController : UIViewController {}
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#property (nonatomic, strong) NSMutableData *downloadData;
#end
ViewController.m
#import "ViewController.h"
#import "MapViewAnnotation.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_downloadData = [NSMutableData new];
NSURL *requestURL = [NSURL URLWithString:#"OMITTED/apptest/locations.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:requestURL];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_downloadData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
id parsed = [NSJSONSerialization JSONObjectWithData:_downloadData options:kNilOptions error:nil];
for (NSDictionary *pointInfo in parsed)
{
NSLog([parsed objectForKey:#"name"]);
double xCoord = [(NSNumber*)[parsed objectForKey:#"lat"] doubleValue];
double yCoord = [(NSNumber*)[parsed objectForKey:#"lon"] doubleValue];
CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(xCoord, yCoord);
MKPointAnnotation *point = [MKPointAnnotation new];
point.coordinate = coords;
point.title = [parsed objectForKey:#"name"];
[self.mapView addAnnotation:point]; // or whatever your map view's variable name is
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewDidUnload {
[super viewDidUnload];
// ARC Problem --- [_mapView release];
self.mapView = nil;
}
#end
With iOS 5 there's a JSONSerializer class that can convert the raw JSON data from your URL into an array or dictionary as appropriate.
You'll need to download the data from the server:
NSURL *requestURL = [NSURL URLWithString:#"<your url here>"];
NSURLRequest *request = [NSURLRequest requestWithURL:requestURL];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
Then you'll add these delegate methods:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_downloadData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
id parsed = [NSJSONSerialization JSONObjectWithData:_downloadData options:kNilOptions error:nil];
}
_downloadData is an instance variable or property of your class of type NSMutableData.
That parsed variable will contain your data from the server. It's probably an array if it's a list of points, so you can iterate through it using fast enumeration:
for (NSDictionary *pointInfo in parsed) {
double xCoord = [(NSNumber*)[parsed objectForKey:#"<key for lat coord>"] doubleValue];
double yCoord = [(NSNumber*)[parsed objectForKey:#"<key for long coord>"] doubleValue];
CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(xCoord, yCoord);
MKPointAnnotation *point = [[MKPointAnnotation new] autorelease];
point.coordinate = coords;
point.title = [parsed objectForKey:#"<key for title>"];
[self.mapView addAnnotation:point]; // or whatever your map view's variable name is
}
I have an open source project on GitHub that uses the serializer with the NSCoding protocol so you can automatically create instances right from the JSON stream.
It's here.

show images on tabelview that are come from webservice

I have used the below code. In this code I am showing images that are coming from the webservices. To increase the scroll speed of tabelview I use UIImageView+WebCache it increase the scrolling speed fast but image is show when I touch the imageview. How to show the images when tabelview is display
NSString *str=[self.uploadimagearry objectAtIndex:indexPath.row];
// NSString *str1=[str stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL *uploadimageURL = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// NSData *imgdata=[NSData dataWithContentsOfURL:uploadimageURL];
//UIImage * uploadimage = [UIImage imageWithData:imgdata];
cell.imageView.frame=CGRectMake(0, -15, 50, 35);
//[cell.imageView setImageWithURL:uploadimageURL];
[cell.imageView setImageWithURL:uploadimageURL];
You have to start NSUrlConnection in a different run-loop, so that you receive data while the table is scrolling.
Just check out below examples :
LazyTableImages
Lazy loading multiple images on background threads on the iPhone
//JImage.h
#import <Foundation/Foundation.h>
#interface JImage : UIImageView {
NSURLConnection *connection;
NSMutableData* data;
UIActivityIndicatorView *ai;
}
-(void)initWithImageAtURL:(NSURL*)url;
#property (nonatomic, retain) NSURLConnection *connection;
#property (nonatomic, retain) NSMutableData* data;
#property (nonatomic, retain) UIActivityIndicatorView *ai;
#end
//JImage.m
#import "JImage.h"
#implementation JImage
#synthesize ai,connection, data;
-(void)initWithImageAtURL:(NSURL*)url {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self setContentMode:UIViewContentModeScaleToFill];
if (!ai){
[self setAi:[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]];
[ai startAnimating];
[ai setFrame:CGRectMake(27.5, 27.5, 20, 20)];
[ai setColor:[UIColor blackColor]];
[self addSubview:ai];
}
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
if (data==nil) data = [[NSMutableData alloc] initWithCapacity:5000];
[data appendData:incrementalData];
NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[data length]];
NSLog(#"resourceData length: %d", [resourceLength intValue]);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection error...");
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[ai removeFromSuperview];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[self setImage:[UIImage imageWithData: data]];
[ai removeFromSuperview];
}
#end
//Include the definition in your class where you want to use the image
-(UIImageView*)downloadImage:(NSURL*)url:(CGRect)frame {
JImage *photoImage=[[JImage alloc] init];
photoImage.backgroundColor = [UIColor clearColor];
[photoImage setFrame:frame];
[photoImage setContentMode:UIViewContentModeScaleToFill];
[photoImage initWithImageAtURL:url];
return photoImage;
}
//How to call the class
UIImageView *imagV=[self downloadImage:url :rect];
//you can call the downloadImage function in looping statement and subview the returned imageview.
//it will help you in lazy loading of images.
//Hope this will help

Links inside Pdf on Webview are not opening in a browser in iPhone

I have parsed urls of pdfs and showing pdf on a webView, but my Links inside webviews are not opening in a browser.i have not used CGPDFDocument. my code is simple :). can anyone help me out.i have seen many similar questions but all are using Quartz.
code :-
#class AppDelegate_iPhone;
#interface PdfShowViewController : UIViewController<UIWebViewDelegate> {
IBOutlet UIWebView *pdfWebview;
AppDelegate_iPhone *appDelegate;
NSMutableData *receivedData;
IBOutlet UIActivityIndicatorView *myIndicator;
IBOutlet UIProgressView *progress;
NSURLRequest* DownloadRequest;
NSURLConnection* DownloadConnection;
long long bytesReceived;
long long expectedBytes;
IBOutlet UILabel *downloadLabel;
}
#property (nonatomic,retain) IBOutlet UILabel *downloadLabel;
#property (nonatomic,retain) IBOutlet UIWebView *pdfWebview;
#property (nonatomic,retain) IBOutlet UIActivityIndicatorView *myIndicator;
#property (nonatomic,retain) IBOutlet UIProgressView *progress;
#property (nonatomic,retain) NSMutableData *receivedData;
#property (nonatomic, readonly, retain) NSURLRequest* DownloadRequest;
#property (nonatomic, readonly, retain) NSURLConnection* DownloadConnection;
#property (nonatomic, retain, readwrite) NSURL *openURL;
-(IBAction)onTapBack;
#end
#implementation PdfShowViewController
#synthesize pdfWebview,myIndicator,progress,receivedData,DownloadRequest,DownloadConnection,downloadLabel,openURL;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
unsigned char byteBuffer[[receivedData length]];
[receivedData getBytes:byteBuffer];
NSLog(#"Data === %ld",receivedData);
NSInteger receivedLen = [data length];
bytesReceived = (bytesReceived + receivedLen);
NSLog(#"received Bytes == %f",bytesReceived);
if(expectedBytes != NSURLResponseUnknownLength)
{
NSLog(#"Expected Bytes in if == %f",expectedBytes);
NSLog(#"received Bytes in if == %f",bytesReceived);
float value = ((float) (bytesReceived *100/expectedBytes))/100;
NSLog(#"Value == %f",value);
progress.progress=value;
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
expectedBytes = [response expectedContentLength];
NSLog(#"%f",expectedBytes);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[myIndicator stopAnimating];
[myIndicator removeFromSuperview];
[progress setHidden:YES];
[downloadLabel setHidden:YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:#"iPhonePdf.pdf"];
unsigned char byteBuffer[[receivedData length]];
[receivedData getBytes:byteBuffer];
[self.receivedData writeToFile:pdfPath atomically:YES];
[DownloadConnection release];
//Now create Request for the file that was saved in your documents folder
NSURL *url = [NSURL fileURLWithPath:pdfPath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[pdfWebview setScalesPageToFit:YES];
[pdfWebview loadRequest:requestObj];
}
-(BOOL)webView:(UIWebView *)webView1 shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *requestURL = [request URL];
if(navigationType==UIWebViewNavigationTypeLinkClicked)
{
[[UIApplication sharedApplication] openURL:requestURL];
return NO;
}
else
{
return YES;
}
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
pdfWebview.delegate = self;
appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];
[downloadLabel setText:#"Downloading..."];
[downloadLabel setHidden:NO];
[myIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
myIndicator.hidesWhenStopped = YES;
[myIndicator startAnimating];
// NSString *urlString = [appDelegate.currentBookPressed stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString *urlString = [appDelegate.currentBookPressed stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSLog(#"The Url Stirng=======%#",urlString);
NSURL *targetURL = [NSURL URLWithString:urlString];
//NSLog(#"Trageted String ------======++++++++%#",targetURL);
DownloadRequest = [NSURLRequest requestWithURL:targetURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:1200.0];
DownloadConnection = [[NSURLConnection alloc] initWithRequest:DownloadRequest delegate:self];
if (DownloadConnection) {
receivedData = [[NSMutableData data]retain];
}
[pdfWebview setScalesPageToFit:YES];
[pdfWebview loadRequest:DownloadRequest];
}
-(IBAction)onTapBack
{
[self dismissModalViewControllerAnimated:YES];
}
#end
here is the link which i am trying to open but not opening :-
No, links inside pdf files loaded in a UIWebView won't open when you tap them by default.
You can go the hard way and parse the links out using Quartz as is shown in this other post I answered.
Or, instead of loading a pdf, can you convert the content you are loading to an html file instead? That would be easier, and the links should work then.
You have to use below delegate method
-(BOOL)webView:(UIWebView *)webView1 shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *requestURL = [request URL] ;
if(navigationType==UIWebViewNavigationTypeLinkClicked)
{
[[UIApplication sharedApplication] openURL:requestURL];
return NO;
}
else
{
return YES;
}
}