How to save webpages and open it after clicking? - ios

enter image description here
Attached is screenshot for my view controller. When users search on internet, how do I realize these functions?
save current web page ( maybe go to another view controller after clicking "save")
my idea is to save on a table view, with a brief title
after clicking the title, shows contents of the whole page saved.
if users reply emails on some website with attachments, they can also save the attachments (word, pdf,etc) in the app.
I initialized the web view with google. The problem is the page to be saved can be any NSURL, I have no idea how to do that.
Or you can advise some way totally different, as long as I can realize these functions.

For future reference you should include some code... but anyway, I would just set the NSURL as a string of each webpage in NSUserDefaults then call the main applications open URL method.
Like...
NSUserDefaults.standardUserDefaults.setObject("YourURL" forKey: "URLKey")
NSUserDefaults.standardUserDefaults.synchronize()
Then retrieve it like...
if let urlString = NSUserDefaults.standardUserDefaults.objectForKey("URLKey") {
let url = NSURL(string: urlString)
UIApplicationSharedApplication.openURL(url)
}
I wrote this code off the top of my head so it might need some tweaking but I hope it helps!

If you want the user to save many webpages, you should not use NSUserDefaults to achieve it. You should use something called CoreData. This is because NSUserDefaults can only save one url at a time. If you want to save another, you need another key to do so.
Here is basically what you need to do. You create a new Core Data Model file (.xcdatamodeld). Add an entity called SavedUrls. Add a property to that entity called urlString. Then generate a NSManagedObject subclass.
To save data, get the managed object context from the App Delegate. Create a new instance of SavedUrls using the inherited initializer. And change the property to the url to be saved. Then just call save on the context.
To get data back, get the managed object context and create an NSFetchRequest to fetch from the database.
Learn more here:
https://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial

Related

List of images with their properties

My problem:
In my app there are a lot of images. I have a list of categories which user can choose for filtering all images by chosen category. User can't delete/edit these images, and can't add smth in it, so I guess I don't need the Core Data.
So my question is:
How and where in my project should I store and manage images' names with their properties, so I could use this list with files' names and their properties from any ViewController?
Finally, if you didn't get it: It should look like this:
1.Name: "imagename.jpg", Category: "Somecategory")
2.Name: "imagename2.jpg", Category: "Anothercategory")
Thank you.
If you want to store your images under NSDocuments with a susbfolder , I think you can do it without using database and Core Data .
Let's think a scenerio for you based on Model View Controller(MVC) structure:
You want to store images with an special properties like NSString *categories and NSString *filePath under NSFileManager with a subfolder . Encode your object and convert it to NSData. You need an Model class(it's subclass of NSObject)
that keeps your properties. You need to learn how to save a file to your Documents path. This blog is very good but it's Objective C. This is your Model and your image object.
Create a View that shows your images UICollectionView (just an example) and collect them with your image object. Modify it how you want!
Create your Controller class and do all actions here. Like saving image to path, getting image from path, all UIButton actions etc... Add your View to this class,decode your NSData to your image object show it.
This is the logic of an example, you can do it according to your necessities.
The way you should following is saving your image data to NSDocuments , search it. I advice you to learn MVC Stucture
Hope this give you an idea to start.

How to store form data in a swift app

I'm working on my first app and I need some help understanding what kind of data storage I need. I'm familiar with PHP, SQL, and databases but I don't know where to start with this project.
The app is pretty much a basic form with text fields, pickers, and uploaded images. At the end, the user will press submit and all of their data will be sent in an email.
What is the best way to store their data, so the user can go to previous screens and have their previously entered info still there. And then what is the best way to store the data after they press submit to send it in an email?,
Thanks so much for your help!
If it's just form data that you're storing once for submission, for simplicity sake, I recommend just stuffing it in a global dictionary that you can access from different views. Swift makes this easy by just adding an empty swift file and defining your dictionary at the top:
var myFormData: [String: AnyObject]()
You can now access "myFormData" form anywhere in your app, add and remove stuff from it.
You shouldn't technically need to "reload previous views" because of the way the navigation stack works. Anything you go back to should hold it's info.
If you really need to save the data to allow the user to close the app and then pick up where they left off much later, then I recommend simply kicking your dictionary to NSUserDefaults. It doesn't sound like something that needs to involve a database.
You can use a class called NSUserDefaults
var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() //make an instance
defaults.setObject("Bob", forKey: "myName") //storing a value
defaults.synchronize() //synchronize data
println(defaults.objectForKey("myName")!) //retrieve the data

Update NSManagedObject into Core Data

So I have a tabbed application. The first tab allows a user to enter information in ~20 fields that describe a NSManagedObject. They are then able to save this into core data, and that works just fine.
The second tab is a TableView of all of the existing submissions. Now when a user clicks on a cell in the TableView, it will open up the first tab and repopulate all of the fields that were originally saved into core data. When the user clicks save again, I want the existing submission in core data to be updated, instead of a new insertion into core data.
I have found a lot of information saying that I should make a fetch request and then update it like that. But that seems redundant to me because I already have the object that was saved passed to the first tab/ViewController.
If you could point me to some code that would help my situation or describe a way you might accomplish this scenario, I would greatly appreciate it!
Since you have a reference to the NSManagedObject in the first tab, you can update its properties to the new values when the user saves. You can then save the changes to your NSManagedObject (let's call it myObject for simplicity) by calling [[myObject managedObjectContext] save:&error] where error is an NSError *.

How to display a picture using data from ViewData.Model [as opposed taking data from a remote location using, for instance, Url.Action]

I'm doing kind of wizard application that captures information on Contacts. So, before saving to DB, all data collected during the process are kept in memory as model's properties (using serialization/deserialization). Data collected includes the uploaded picture of the contact. The last page is called "preview" where I display all the information entered during the process before saving them to the DB. On that preview page, I'd like also to display the photo of the contact on left and his information on the right.
It is easier to display picture using the following statements
<img src = ".../.../Content/MyPicture" />
<img src = "<% = Url.Action("Action", "Controller", "routevalue")%>"/>
How about if the data is not located in remote locations like in the above samples, but rather in the ViewData.Model?
By the way, my model, ContactData, has 2 properties ImageData and ImageMimeType holding data for the picture. How do I use them?
Thanks for helping
Usually, you'd store it in a session variable, and when the request for the image comes around you'll feed it whatever is in the session. There are a couple of things that need to work in order for this to function, but usually it does.
There is one more option, if the image is small, you can inline it directly into your document using a data uri, like so:
<img src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP
C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA
AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J
REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq
ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0
vr4MkhoXe0rZigAAAABJRU5ErkJggg==" />
(example is stolen from wikipedia, paste uri into your location bar, and it'll show you an image of a red dot). You'll need to base64 encode the binary data (or url-encode, but base64 is usually preferable for binary data).
Roe,
It took me 2 days and many frustrations just to realize what you meant by storing data in the session state variable. Anyway, below is the solution for anyone to take advantage of.
I, first, put data needed to display in the session state variables
public ActionResult PreviewPage()
{
Session["ImageData"] = contactData.ImageData;
Session["ImageMimeType"] = contactData.ImageMimeType;
return View(contactData);
}
I also created a action method to send data to view. This is where all the magics are done. This action picks up data contained in the Session variables
public FileContentResult GetImage()
{
return File((byte[]Session["ImageData"], (string)Session["ImageMimeType"]);
}
Finally, this how I view accesses to that data without having to fetch needed from a database.
<img src = "<% = Url.Action("GetImage", "Contact")%>" />
It was important that I be able to understand how this works because I'll be doing more of Wizards-like applications in the future.
Thanks very much for helping.

ASP.NET MVC - Sharing Session State Between Controllers

I am still mostly unfamiliar with Inversion of Control (although I am learning about it now) so if that is the solution to my question, just let me know and I'll get back to learning about it.
I have a pair of controllers which need to a Session variable, naturally nothing too special has happen because of how Session works in the first place, but this got me wondering what the cleanest way to share related objects between two separate controllers is. In my specific scenario I have an UploadController and a ProductController which work in conjunction with one another to upload image files. As files are uploaded by the UploadController, data about the upload is stored in the Session. After this happens I need to access that Session data in the ProductController. If I create a get/set property for the Session variable containing my upload information in both controllers I'll be able to access that data, but at the same time I'll be violating all sorts of DRY, not to mention creating a, at best, confusing design where an object is shared and modified by two completely disconnected objects.
What do you suggest?
Exact Context:
A file upload View posts a file to UploadController.ImageWithpreview(), which then reads in the posted file and copies it to a temporary directory. After saving the file, another class produces a thumbnail of the uploaded image. The path to both the original file and the generated thumbnail are then returned with a JsonResult to a javascript callback which updates some dynamic content in a form on the page which can be "Saved" or "Cancelled". Whether the uploaded image is saved or it is skipped, I need to either move or delete both it and the generated thumbnail from the temporary directory. To facilitate this, UploadController keeps track of all of the upload files and their thumbnails in a Session-maintained Queue object.
Back in the View: after the form is populated with a generated thumbnail of the image that was uploaded, the form posts back to the ProductsController where the selected file is identified (currently I store the filename in a Hidden field, which I realize is a horrible vulnerability), and then copied out of the temp directory to a permanent location. Ideally, I would like to simply access the Queue I have stored in the Session so that the form does not need to contain the image location as it does now. This is how I have envisioned my solution, but I'll eagerly listen to any comments or criticisms.
A couple of solutions come to mind. You could use a "SessionState" class that maps into the request and gets/sets the info as such (I'm doing this from memory so this is unlikely to compile and is meant to convey the point):
internal class SessionState
{
string ImageName
{
get { return HttpContext.Current.Session["ImageName"]; }
set { HttpContext.Current.Session["ImageName"] = value; }
}
}
And then from the controller, do something like:
var sessionState = new SessionState();
sessionState.ImageName = "xyz";
/* Or */
var imageName = sessionState.ImageName;
Alternatively, you could create a controller extension method:
public static class SessionControllerExtensions
{
public static string GetImageName(this IController controller)
{
return HttpContext.Current.Session["ImageName"];
}
public static string SetImageName(this IController controller, string imageName)
{
HttpContext.Current.Session["ImageName"] = imageName;
}
}
Then from the controller:
this.SetImageName("xyz");
/* or */
var imageName = this.GetImageName();
This is certainly DRY. That said, I don't particularly like either of these solutions as I prefer to store as little data, if any, in session. But if you're intent is to hold onto all of this information without having to load/discern it from some other source, this is the quickest (dirtiest) way I can think of to do it. I'm quite certain there's a much more elegant solution, but I don't have all of the information about what it is you're trying to do and what the problem domain is.
Keep in mind that when storing information in the session, you will have to dehydrate/rehydrate the objects via serialization and you may not be getting the performance you think you are from doing it this way.
Hope this helps.
EDIT: In response to additional information
Not sure on where you're looking to deploy this, but processing images "real-time" is a sure fire way to be hit with a DoS attack. My suggestion to you is as follows -- this is assuming that this is public facing and anyone can upload an image:
1) Allow the user to upload an image. This image goes into the processing queue for background processing by the application or some service. Additionally, the name of the image goes into the user's personal processing queue -- likely a table in the database. Information about background processing in a web app can be found # Schedule a job in hosted web server
2) Process these images and, while processing, display a "processing graphic". You can have an ajax request on the product page that checks for images being processed and trys to reload them every X seconds.
3) While an image is being "processed", the user can opt out of processing assuming they're the one that uploaded the image. This is available either on the product page(s) that display the image or on a separate "user queue" view that will allow them to remove the image from consideration.
So, you end up with some more domain objects and those objects are managed by the queue. I'm a strong advocate of convention over configuration so the final destination of the product image(s) should be predefined. Something like:
images/products/{id}.jpg or, if a collection, images/products/{id}/{sequence}.jpg.
You then don't need to know the destination in the form. It's the same for all images.
The queue then needs to know where the temp image was uploaded and what the product id was. The queue worker pops items from the queue, processes them, and stores them accordingly.
I know this sounds a little more "structured" than what you originally intended, but I think it's a little cleaner.
Is there complete equivalence between the UploadController and ProductController?
As files are uploaded by the UploadController, data about the upload is stored in the Session. After this happens I need to access that Session data in the ProductController.
As I read that the UploadControl needs read and write access to Upload data, the ProductController needs only read.
If that's true then you can make it clear by using an immuatable wrapper around the upload information and have the UploadController put that into the session.
The Session itself is by definiton a public shared noticeboard, decouples explicit relationships at the cost of allowing anyone to get and put. You could allow the ProductController to know about the UploadController and hence remove the need for passing the upload information via the session. My instinct is that the upload info is interesting to the public, so using Session is reasonable.
I don't see any DRY violation here, we are explicitly trying to separate responsibilities.

Resources