I am trying to download my image and store into a directory. Every thing is working fine before updating the names of images on the server end with spaces. I am handling the spaces with the following code.
NSString *newString = [getImageUrl stringByReplacingOccurrencesOfString:#" "
withString:#"%20"];
After that I am getting the final String of URL as given below
http://www.retail-king.com/image/data/men%20jeans/pd%201/5.jpg
When I open this url in browser then the image is showing but I cannot see and download the image with this url in the app.
I am calling the following method to download the image.
-(void)downloadImageWithPath:(NSString *)_path andURL:(NSString *)_url
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:_url]];
NSLog(#"pic file = %#",_path);
NSLog(#"ASI http pic url:%#",[[request url] description]);
// [request setDownloadProgressDelegate:self];
[request setShowAccurateProgress:YES];
request.shouldContinueWhenAppEntersBackground=YES;
[request setDownloadDestinationPath:_path];
[request setTimeOutSeconds:30];
// [request setDelegate:self];
[request setStartedBlock:^{
NSLog(#"request started pic");
}];
[request setCompletionBlock:^{
// Use when fetching text data
NSLog(#"request completed pic");
currentPicsCount++;
if (currentPicsCount == picsCount && totalPicsDownload ) {
NSLog(#"All pics have downloaded");
totalPicsDownload = false;
[[SingltonClass getLoadingClassReference] dataSynced];
}
}];
[request setFailedBlock:^{
NSLog(#"request failed pic");
picsCount--;
}];
[request startAsynchronous];
}
setFailedBlock is called. Which shows pic is failed to download.
Your question is ambiguous. I quickly ran a test on the URL and was able to see the downloaded image. This might not be an ideal solution, but you can understand what's going on. I used UIWebView to display the image, and the for you the tricky part could be to set the bounds of CGRectMake. How are you downloading and displaying the images?
Here is my code if it helps.
- (void)viewDidLoad
{
[super viewDidLoad];
// Added space between keyword men and jeans
NSString *url = #"http://retail-king.com/image/data/men jeans/pd%201/5.jpg";
url = [url stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
// Check for URL
NSLog(#"Final Url = %#",url);
// Displaying it on webview
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
NSURL *targetURL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
// Program to check if the image is downloaded in directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *localFilePath = [paths objectAtIndex:0];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[thedata writeToFile:localFilePath atomically:YES];
}
The image was successfully downloaded at -
/Users/raurora/Library/Application Support/iPhone Simulator/7.1/Applications/554A5C94-1D29-42F0-886D-751CD3DFB155/Library/Caches/com.stackoverflow.doubt/fsCachedData/
Related
I'm trying to call an API and bring back menu items. My string seems to contain data because when I put it into a browser, I'm getting JSON.
NSString *urlString = [NSString stringWithFormat:#"https://api.nutritionix.com/v1_1/search/subway?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=MY_APP_ID&appKey=MY_APP_KEY"];
NSURL *url = [NSURL URLWithString:urlString];
My "urlString" contains a lot of information, but when I put a breakpoint on the NSURL object, it says it returns "nil".
EDIT: Removed spaces however the error persists.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"GET"];
[request setURL:[NSURL URLWithString:urlString]];
NSHTTPURLResponse *responseCode = nil;
NSError *error = [[NSError alloc] init];
NSData *ResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:ResponseData options:kNilOptions error:nil];
itemName = dataDictionary[#"item_name"];
NSLog(#"%#", itemName);
EDIT: Added request code
Ok, I have found something interesting about your url
You just forgot about string format. Every percent sign cry to you: 'I want to be replaced with something you gain to me!'
So, to prevent such behavior, you need to hide every percent with another percent: %%
-(void)doNSURLTestOne{
NSString *urlString = [NSString stringWithFormat:#"https://api.nutritionix.com/v1_1/search/subway?results=0%%3A20&cal_min=0&cal_max=50000&fields=item_name%%2Cbrand_name%%2Citem_id%%2Cbrand_id&appId=MY_APP_ID&appKey=MY_APP_KEY"];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"is url nil? %#", url);
NSLog(#"is urlString ok? %#", urlString);
}
But I prefer to use AFNetworking library for net part
UPD: better choice to use another clean NSString ( thanks #rmaddy )
-(void)doNSURLTestTwo{
NSString *urlString = #"https://api.nutritionix.com/v1_1/search/subway?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=MY_APP_ID&appKey=MY_APP_KEY";
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"is url nil? %#", url);
NSLog(#"is urlString ok? %#", urlString);
}
I'm developing an app for iOS 8.1 using Xcode 6.1.1
And I want to download a PDF from internet, store in to my iPad and then load it into a webview; this is the PDF test:
this is the result I get on iPad after trying to display it on my WebView:
this is my code so far...
// Get the PDF Data from the url in a NSData Object
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.ferc.gov/docs-filing/elibrary/larg-file.pdf"]];
// Store the Data locally as PDF File
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolderPath = searchPaths[0];
NSString *archivePath = [documentFolderPath stringByAppendingPathComponent:#"larg-file.pdf"];
[pdfData writeToFile:archivePath atomically:YES];
// Now create Request for the file that was saved in your documents folder
NSURL *url = [NSURL fileURLWithPath:archivePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_webView setUserInteractionEnabled:YES];
[_webView setDelegate:self];
[_webView loadRequest:requestObj];
How do I make this work?
EDIT: this is the answer
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolderPath = searchPaths[0];
NSString *archivePath = [documentFolderPath stringByAppendingPathComponent:#"larg-file.pdf"];
if (![Functions isAlreadyStoredinDeviceFileWithName:#"larg-file.pdf"]) {
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.ferc.gov/docs-filing/elibrary/larg-file.pdf"]];
[pdfData writeToFile:archivePath atomically:YES];
}
// Now create Request for the file that was saved in your documents folder
NSURL *url = [NSURL fileURLWithPath:archivePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_webView setUserInteractionEnabled:YES];
[_webView setDelegate:self];
[_webView loadRequest:requestObj];
This code:
NSString *resourceDocPath = [[NSString alloc] initWithString:[
[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
stringByAppendingPathComponent:#"Documents"]];
Attempts to formulate a directory within the application bundle. You do not have write access to the application bundle. Your file therefore isn't saved.
Check out -[NSFileManager URLsForDirectory:inDomains:] or NSSearchPathForDirectoriesInDomains for how to get the path to the user's documents folder.
I would to follow any user with the help of my application. Can anybody suggest me what to do ? As I read the Instagram API from here. But not getting proper idea what to do.
You can do this way :-
NSString *urlString=[NSString stringWithFormat:#"https://api.instagram.com/v1/users/%#/relationship?access_token=%#",<user id>,<access token>];
NSURL* url = [NSURL URLWithString:urlString];
theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:1000.0];
NSString *parameters=#"action=follow";
[theRequest setHTTPBody:[parameters dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest setHTTPMethod:#"POST"];
To follow we only need client_id
First of all create a client_id by registering your app on Instagram
and open given Url in webView.
NSString *urlAddress =[NSString stringWithFormat:#"https://instagram.com/oauth/authorize/?client_id=%#&redirect_uri=http://appbellfitness.com/&response_type=token&scope=likes+comments+relationships",client_id];
NSURL *nsurl=[NSURL URLWithString:urlAddress];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[webview loadRequest:nsrequest];
webview.delegate = self;
And add WebView delegate to it.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *orignalUrl =[request.URL absoluteString];
if ([orignalUrl hasPrefix:CALLBACKURL])
{
NSArray* parts = [orignalUrl componentsSeparatedByString: #"="];
request_token = [parts objectAtIndex: 1];
NSString *myurl =[NSString stringWithFormat:#"https://api.instagram.com/v1/users/25025320/relationship?access_token=%#",request_token];
NSString *action=#"action=follow";
BsyncTask *task = [[BsyncTask alloc]init];
[task asynchronousPost:action url:myurl callerName:#"followTask"];//post this as you like
task.recieveAsyncResponse = self;
}
return YES;
}
shouldStartLoadWithRequest
I check it starts with my redirect Uri then I get the access token by seperating the url on the basis of = sign. and then i post it using my class you can post it as you like and get response.
I am having an app in which I am opening a PDF file from a url.
I am successfully able to open it in a webView.
Now I want to download that PDF file and save it in my documents folder and want to send that PDF file in my mail.
I searched a lot and found the best solution below.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"myfile.pdf"];
if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf"]];
//Store the downloaded file in documents directory as a NSData format
[pdfData writeToFile:filePath atomically:YES];
}
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView setUserInteractionEnabled:YES];
[webView setDelegate:self];
webView.scalesPageToFit = YES;
[webView loadRequest:requestObj];
But when i try this code, it gives me error saying failed to find PDF header: `%PDF' not found
I am even not able to open my PDF also.
I know same questions are asked before but I am not able to solve this error right now.
I don't know what I am doing wrong over here.
Sorry for the inconvenience.
Please help me with this.
try this code for downloading & saving your pdf file
UIActivityIndicatorView *indicator=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[indicator startAnimating];
NSLog(#"Downloading Started");
NSString *urlToDownload = #"http://gradcollege.okstate.edu/sites/default/files/PDF_linking.pdf";
NSURL *url = [NSURL URLWithString:urlToDownload];
NSURLRequest *request=[[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:120.0f];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
[indicator stopAnimating];
if (!connectionError) {
if ( data )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"myfile.pdf"];
//saving is done on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[data
writeToFile:filePath atomically:YES];
NSLog(#"File Saved !");
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_rssWebView setUserInteractionEnabled:YES];
//[_rssWebView setDelegate:self];
[_rssWebView loadRequest:requestObj];
});
}
}
}];
If convert to string server response, that you got in NSData *pdfData, you will see next:
<!DOCTYPE html>
<html>
<head>
<title>iOS Developer Library</title>
<meta charset="utf-8">
<script>
var content_page = "navigation";
var href = window.location.href;
if (window.location.href.match('#')) {
var newhref = href.replace('#', '');
newhref = newhref.replace('%23', '#');
window.location.href = newhref;
}
else {
console.log(content_page);
console.log(content_page.match("content_page"));
if(content_page.match("content_page")) {
window.location.href = './navigation';
}
else {
window.location.href = "./" + content_page;
}
}
</script>
</head>
<body>
</body>
<script type="text/javascript" src="/library/webstats/pagetracker.js"></script>
<script type="text/javascript">
if(typeof PageTracker !== 'undefined') {
if(window.addEventListener) {
window.addEventListener("load", function(){PageTracker.logPageLoad()},false);
} else if(window.attachEvent) {
window.attachEvent("onload",function(){PageTracker.logPageLoad()});
}
}
</script>
</html>
This only web page, which, as I can assume, will forward you to document with another URI:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf. So you must use this url if you want to download .pdf file
Also, pay attention on #pawan's answer, and use his approach to avoid download files in main thread
I am uploading a JSON document from my app to a server on the web, and I am able to do this successfully. However, what I need to do now is detect when there is no WiFi or 3G connectivity and prompt the user with an alert that informs the user that the app is unable to connect, and then give them the option to save the JSON document as a .plist file locally.
Here is the code that I have thus far:
This is my method that uploads my JSON document to the server:
- (void) sendJsonDoc:(NSString *)jDoc {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://myWebsite.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setValue:[NSString stringWithFormat:#"%d", [jDoc length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[jDoc dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSLog(#"%d", code);
}
Here is the code that I have in order to save the JSON document locally as a plist file:
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:#"jsonDoc.plist"];
// If the file doesn't exist in the Documents Folder, copy it.
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:#"jsonDoc" ofType:#"plist"];
[fileManager copyItemAtPath:sourcePath toPath:path error:nil];
}
// Load the Property List.
NSString *loadJSON = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
How do I detect in my sendJsonDoc method when there is no connection and issue an alert to the user that prompts them that there is no connection, and if they want to save the document locally?
Check out the Reachability framework/library.
tonymillion made a nice version of the Apple supplied one that has been adapted to use ARC and adds support for blocks as well. The readme on github also explains how you can subscribe to notifications for the change of connection :)
Check out the project here