Where my pdf file save in iPhone - ios

I have use this code for download pdf in iPhone on button click are as:-
- (IBAction)download:(id)sender {
self.downloadedMutableData = [[NSMutableData alloc] init];
urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://www.tutorialspoint.com//objective_c/objective_c_tutorial.pdf"]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60.0];
self.connectionManager = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
}
#pragma mark - Delegate Methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"%lld", response.expectedContentLength);
self.urlResponse = response;
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.downloadedMutableData appendData:data];
progress.progress = ((100.0/self.urlResponse.expectedContentLength)*self.downloadedMutableData.length)/100;
if (progress.progress == 1) {
progress.hidden = YES;
} else {
progress.hidden = NO;
}
float percentage=((100.0/self.urlResponse.expectedContentLength)*self.downloadedMutableData.length);
percentageLbl.text = [NSString stringWithFormat:#"%.0f%%",percentage];
NSLog(#"%.0f%%",percentage);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Finished");
if (self.downloadedMutableData)
{
NSString *filePath = [NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"Pdf.pdf"];
[self.downloadedMutableData writeToFile:filePath atomically:YES];
}
}
I don't know where my pdf file is save in iPhone. I want to save pdf file in Gallery in iPhone.
Can you help me?

Related

Fetch Pagination URL Data with NSURLConnection in iOS

i am newbie in iOS make an app that contain JSON Parsing data for that i use NSURLConnection and fetch data but here my URL Contain Pagination so, i want to fetch pagination data when tableView scroll for that i write a code like as
- (void)viewDidLoad
{
page=0;
NSString *path = [NSString stringWithFormat:#"http://isp.ebizzprojects.com/webservices/testimonial.php?page=%d",page];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
And Also I send second request when my table view scroll like as
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSInteger currentOffset = scrollView.contentOffset.y;
NSInteger maximumOffset = scrollView.contentSize.height- scrollView.frame.size.height;
if (maximumOffset - currentOffset <= 0)
{
page = page + 1;
[self getData];
}
}
-(void)getData
{
NSString *path = [NSString stringWithFormat:#"http://isp.ebizzprojects.com/webservices/testimonial.php?page=%d",page];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
And NSURLConnection delegate method like as
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[_parsedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_parsedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
_parsedData = nil;
_parsedData = [[NSMutableData alloc]init];
[[[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Connection Error" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil]show];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString =[[NSString alloc]initWithData:_parsedData encoding:NSUTF8StringEncoding];
NSDictionary *loDict = [responseString JSONValue];
self.responceArray=[loDict valueForKey:#"description"];
self.nameArray=[loDict valueForKey:#"name"];
self.testimonialTable.hidden=FALSE;
[self.testimonialTable reloadData];
}
From this my code when i scroll table view then i got only second page data i want to keep both data in to my table view when my tableview scroll please give me solution for this.
Thanks.
You need to add new items to array like, create NSMutableArray for self.responceArray and self.nameArray
[self.responceArray addObjectsFromArray:[loDict valueForKey:#"description"]];
[self.nameArray addObjectsFromArray:[loDict valueForKey:#"name"]];

URL as a string and values in Xcode

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];
}
}

When changing view controllers NSURLConnection delegate not updating the progress bar

I am performing a download through NSURLConnection class and updating a progress bar view according to the received bytes in the NSURLConnection delegate connection didReceiveData.
Everything is working fine when I am on the page where downloading is happening but when I am going to some other view controller and coming back to my downloading page, the connection delegate functions are being called while transition of page but coming back does not upgrade the progress bar.
The code I am using is:
- (IBAction)download:(id)sender {
_currentURL = [NSString stringWithFormat:#"url_to_download"];
NSURL *url =[NSURL URLWithString:_currentURL];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
_receivedData = [[NSMutableData alloc]initWithLength:0];
connection2 = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(#"THE STATUS CODE IS %d",[httpResponse statusCode]);
statuscode = [httpResponse statusCode];
NSLog(#"into didReceiveResponse");
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[_receivedData setLength:0];
expectedBytes = [response expectedContentLength];
NSLog(#"EXPECTED BYTES:%ld",expectedBytes);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"into did receivedata");
[_receivedData appendData:data];
self.setting.enabled = NO;
float progressive = (float)[_receivedData length] / (float)expectedBytes;
[self.progress setProgress:progressive];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
AppDelegate *app = (AppDelegate*) [[UIApplication sharedApplication]delegate];
NSLog(#"into didfailwitherror");
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"connection failed");
}
-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.setting.enabled = YES;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"DOCUMENT DIRECTORY :%#",documentsDirectory);
_imagePath = [documentsDirectory stringByAppendingPathComponent:_fullPath];
NSLog(#"iamge path:%#",_imagePath);
NSLog(#"succeeded");
[UIApplication sharedApplication].networkActivityIndicatorVisible= NO;
NSLog(#"Succeeded! Received %d bytes of data",[_receivedData length]);
// flag= [_receivedData writeToFile:imagePath atomically:NO];
if([_receivedData writeToFile:_imagePath atomically:YES])
{
NSLog(#"write successfull");
app.dl_status = 0;
[HUD hide:YES];
[HUD removeFromSuperview];
HUD = nil;
[self completedDownloadHUD];
[self.download setBackgroundImage:[UIImage imageNamed:#"download.png"] forState:UIControlStateNormal];
}
else{
app.dl_status = 0;
NSLog(#"write failed");
[HUD hide:YES];
[self errorDownloadHUD];
}
NSString *imagePathExtension;
imagePathExtension = [_imagePath pathExtension];
if([imagePathExtension isEqual:#"jpg"])
{
NSLog(#"imagepathextension is jpg");
UIImage *img =[UIImage imageWithContentsOfFile:_imagePath];
UIImageWriteToSavedPhotosAlbum(img, self, #selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
else if([imagePathExtension isEqual:#"mov"])
{
NSLog(#"imagepathextension is mp4");
UISaveVideoAtPathToSavedPhotosAlbum(_imagePath, nil, nil, nil);
}
}
Please tell me how i can retain the value of progress bar while coming back to page and update it.
Change your delegate to this then update the question. I suspect you will find something gets hit with the asserts:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"into didReceiveData");
[_receivedData appendData:data];
assert(_receivedData); // it exists
assert([_receivedData length]); // it also has some data in it
self.setting.enabled = NO;
float progressive = (float)[_receivedData length] / (float)expectedBytes;
assert(expectedBytes > 0);
assert(progressive > 0 && progressive <= 1);
assert(self.progress);
assert(!self.progress.hidden);
assert(!self.progress.alpha > 0.5);
assert(self.progress.window);
[self.progress setProgress:progressive];
}
If you don't get any asserts, you still are getting delegate messages, and the progress bar is not visible (or not moving) then log the value of progressive and/or the progress bar frame.

Show Activity Indicator when fetching JSON data

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];
}

URL Connection ios

I want to create connection from my iphone to my website where I will be retrieving data that needs to be parsed. I am not having any luck so far and am kind of confused in regard to the following delegate methods:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
Are these methods called upon there own from my code or do I manually need to call them? Do I need to declare a delegate anywhere in my .h file?
This is what I have been doing but have had no luck. If anyone can explain it would be appreciated. It says my connection is successful made but the NSLog comes up in the console for didFailWithError.
Thanks
-(void) data: (id) sender
{
NSString *stringToBeSent;
NSURL *siteWithNumbers;
NSString *translation;
NSError *error;
NSString *boo;
sender= [sender lowercaseString];
sender= [sender stringByReplacingOccurrencesOfString:#"," withString:#""];
receivedData= [[NSMutableData alloc] init]; //declared in .h file as NSMutableData
stringToBeSent= [[NSString alloc]
initWithFormat:#"http://xxxx/sql.php? data=%#",sender];
NSURLRequest *theRequest=[NSURLRequest
requestWithURL:[NSURL URLWithString:stringToBeSent]];
NSURLConnection *conn= [[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
//[self createConnectionWithPath:stringToBeSent];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
/* appends the new data to the received data */
NSLog(#"here now1");
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
NSString *stringData= [[NSString alloc]
initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Got data? %#", stringData);
[conn release];
conn = nil;
}
- (void)connection:(NSURLConnection *)
connection didFailWithError:(NSError *)error
{
NSLog(#"fail");
}
//in .h file
#interface yourViewController : UIViewController<NSURLConnectionDelegate>
{
NSMutableData *responseData;
}
// in .m file
-(void) data: (id) sender
{
NSString *strWithURL = [NSString stringWithFormat:#"%#%#",TownsServiceURL,state];
strWithURL = [strWithURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"strConfirmChallenge=%#",strWithURL);
NSURL *myURL = [NSURL URLWithString:strWithURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60];
[NSURLConnection connectionWithRequest:request delegate:self];
}
//Delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection failed with error: %#", [error localizedDescription]);
UIAlertView *ConnectionFailed = [[UIAlertView alloc]
initWithTitle:#"Connection Failed"
message: [NSString stringWithFormat:#"%#", [error localizedDescription]]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[ConnectionFailed show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *s = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
}

Resources