How do you display image from "image_url" in Yelp API? - json

I now understand how to parse and display JSON data, but one thing eludes me: when I call "image_url" and receive the actual URL, how can I instead display the image that it refers to? ...and yes, I am a novice :)
Thanks!

You can do that like this:
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:theUrl]]];
where theUrl is the url in string format. Then simply assign the image to your image view: imageView.image = image - presuming you have set up a UIImageView either in your code, as an IBOutlet or as a tagged object in a view.
NOTE: You may want to have a look at Lazy Table Images to load the image asynchronously.

Related

Swift 4: help decoding a JSON that contains an encoded image using base64

I'm a Swift (and programming) newb, fair warning.
I'm working on an app that is used to track scavenger hunt bonuses. I want to use a JSON file to contain all the bonus data, including a sample image. I see how to encode the image into base64 outside the program, then I can add it into my JSON as a string. Where I'm not certain is what to do with this? From searching I see you would use something like:
class func convertBase64ToImage(imageString: String) -> UIImage {
let imageData = Data(base64Encoded: imageString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
return UIImage(data: imageData)!
}
But I'm not certain if that would simply display said image, or if I need to save that and then call it somehow. The goal is to simply view the image (it is used for reference by the person taking a picture with their placard in the shot).
(I haven't implemented this in code yet, I'm still researching how to do it)
Your code works fine. You can test it out in a Playground easily enough. I used https://www.base64-image.de to Base64 encode a small PNG file and generate a string which I ran through your function. It worked fine.
To answer your direct question, UIImage is simply an image which you can display to the user as follows:
Create a view controller. Add a UIImageView to the view controller and wire up an outlet for it with a suitable name (for example, bonusImageView).
Call your function within the view controller to load the image into the image view.
bonusImageView.image = convertBase64ToImage(imageString: imageString)
Where imageString is the Base64-encoded string you obtained from your JSON.
Whether or not you choose to store the imageString first is up to you. It's not necessary to store it if all you want to do is retrieve it from a server and display it on demand.

how to get html string from NSAttributedString in iOS

I am using UITextview in my app. And I have set allowsEditingTextAttributes property to YES in order to show images and formatted text if user copy pasted from browser into textView and working fine.
I want to retrieve the content back as html from UITextView, is there any way to get it? (I can achieve it using UIWebView but I need to use UITextView only)
Thanks
As far as I know, there is no API provided by Apple to do what you want. You need to get the attributed text as an NSAttributedString from the UITextView and convert it to HTML. There are open-source projects for this however, for example DTCoreText. If you're not looking for very advanced features, you might also be able to build this yourself, just by looping through the string's characters and analyzing the style attributes.
EDIT: Actually, there is an API to do this now! You can use NSAttributedString's dataFromRange:documentAttributes:error:, passing NSHTMLTextDocumentType as the requested document type.
Cheers!
Example (in Swift, can be done similarly in Objective-C):
//Grab the attributed string, convert it to HTML data
let data = try self.textView.attributedText.dataFromRange(
NSMakeRange(0, self.textView.attributedText.length),
documentAttributes: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType]
)
//Convert the UTF-8 data to a string, display it in the text view
self.textView.attributedText = NSAttributedString(
string: NSString(data: data, encoding: NSUTF8StringEncoding)! as String
)
You could take a look at this repository: https://github.com/IdeasOnCanvas/Ashton
To read:
AshtonHTMLReader.h
- (NSAttributedString *)attributedStringFromHTMLString:(NSString *)htmlString;
And to writer:
AshtonHTMLWriter.h
- (NSString *)HTMLStringFromAttributedString:(NSAttributedString *)input;
See if it can help you.

Type in String on Website programmatically

I'd wanted to know how or whether I can type in something in a textField on a website from my iPhone application code. So I want to go to a website where is one textField in the middle and there I would like to type in a specific string. How can I do that in Swift (or Objective-C - I'll figure out how it works in Swift then)? I would really much appreciate any help :)
You can inject JavaScript into an UIWebView by calling the method stringByEvaluatingJavaScriptFromString. You write a piece of JavaScript where you select the input field and modify it's value attribute.
The method is described here:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/index.html#//apple_ref/occ/instm/UIWebView/stringByEvaluatingJavaScriptFromString:
There actually is an article on the web that explains how to do just what you need:
http://iphoneincubator.com/blog/windows-views/how-to-inject-javascript-functions-into-a-uiwebview/
The following is the part you should use (you just have to change the ID in the DOM selector):
[webView stringByEvaluatingJavaScriptFromString:#"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function myFunction() { "
"var field = document.getElementById('field_3');"
"field.value='Calling function - OK';"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"];
[webView stringByEvaluatingJavaScriptFromString:#"myFunction();"];
You can inject javascript from your delegate. For instance, in Obj-C (I don't know swift good enough yet) :
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[_webView stringByEvaluatingJavaScriptFromString:#"doSomeStuff()"];
}
In your case, you'll want to manipulate the DOM to add some text in your textfield - something like this :
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString * javascript_code = #"document.querySelector('input[name=your_input_name]').value = 'Foobaz'";
[_webView stringByEvaluatingJavaScriptFromString:javascript_code];
}
Beware of querySelector though, I'm not sure about its availability in iOS's webview.

How do I display a jpeg image stored in a core data database using html

I have several images soared in a core data database in this way. The entity is named note.
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
image = nil; // free memory
[self createNote];
note.photo_jpeg = imageData;
How do I reference the images in html generated for a web page to display several of these images? I think I need something like this, but I don't know what to put in the IMG SRC=...
NSString *imageHtml = [NSString stringWithFormat:#"<IMG SRC="what do i put here!!!" ALT="Photo" WIDTH=%i HEIGHT=%i>", , )];
[html appendString:imageHtml];
Update This is the solution I used:
[html appendFormat:#"<img alt=\"Embedded Image\" src=\"data:image/jpg;base64,%#\" WIDTH=400 />", [currentNote.photo_jpeg base64EncodedStringWithOptions:0]];
Where currentNote is of type note and is indexed through the notes I am displaying.
You'll need to put the image data inline with the HTML, encoded as base64.
Something like this:
NSData *imageData = // from your code
NSMutableString *html = // mutable string with whatever else you need
[html appendFormat:#"<img alt=\"Embedded Image\" src=\"data:image/jpg;base64,%#\" />", [imageData base64EncodedStringWithOptions:0]];
Keep in mind that this duplicates the image data, so if you're using a lot of images this way, make sure to watch how much memory you're using.
NSData have required methode to get base64 string.
img src="data:image/jpg;base64,HereBase64RepresentationOfYourJPG"
I do not think there is a way to have HTML dip into core data.
I would create a sub-directory for your core data store. In that subdirectory, create a sibling directory to hold your images.
You can store the images as plain jpeg files, and keep the path or bookmark-url to the file in your core data object.
This way, you can still access everything via core data, and the file is available to the HTML as well.
Just include the path to the file as part of the html.

iOS Associate URL with Saved File

My app parses an xml, and builds its own custom HTML from the contents of the article chosen in the XML. When I save an article, I have a class for the action, in which I pass the article title, and the custom HTML to strings within the Save class. The class takes that and saves it to the app using:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[thetitle stringByAppendingString:#".html"]];
NSError *error = nil;
[thehtmlcontents writeToFile:pdfPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
The issue that I have is that if I want to share a saved article via Facebook or Twitter, I can't, because the URL doesn't get saved with everything else. I can pass over the URL easy enough to the Save class, but I'm unsure of what to do with it, so that it stays associated with the article itself. Suggestions?
I'd say you broadly have three options:
Attach some metadata to the file noting the URL it corresponds to
Write out a file format that encapsulates the URL, plus the HTML
Include the URL in the HTML in a manner such that you can retrieve it
no. 1 would probably be best achieved by setting an extended attribute on the file. However, I'm not sure how well iOS supports this, and there may well be issues with it not being preserved in the event of something like restoring the OS.
Are you in a position to implement no. 3 reasonably cleanly? I would say a <meta> tag near the top of the document is best for doing this.
All that said, how important really is it that your HTML is stored in files? To me, this sounds like it could easily be chucked into a dirt simple Core Data database.