Objective с and html

Allow User to create and view HTML files in Objective C?

I’m trying to make an iOS app that allows the user to create an unlimited amount of HTML document and save them into the documents folder of the app. This is sort of like a combo question but how can I display a file that is in the documents dictionary. So my two question are: How to display HTML file that are in the document dictionary And How to allow the user to created unlimited folders and html files Sorry for the double question.

What makes you think there’s a limit? Obviously there’s the physical limit (i.e. storage amount on the iPhone/iPad) but as far as I know there’s no arbitrary limitation on the number of documents an application can create.

2 Answers 2

Saving HTML and Other Text Files to the Documents Directory

First, you need to know the path to your documents directory:

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; 

You can create documents and directories there up to the limits of the device storage. Be aware, however, that only files in the root will show up in iTunes Document Sharing.

Читайте также:  Css flex block width

So, if you have a string htmlContent and a string htmlFilename , you can save it. Do pay attention to the encoding you’re using; the encoding in the HTML header and meta tags (if present) should match the encoding used here.

NSString *htmlPath = [documentsPath stringByAppendingPathComponent:htmlFilename]; [htmlContent writeToFile:htmlPath atomically:NO encoding:NSUTF8StringEncoding error:nil]; 

Displaying HTML Files Within Your App

You can display HTML in a UIWebView . Assuming you have one called webView , you can display any NSURL object in it:

NSURL *stackOverflowAddress = [NSURL URLWithString:@"http://www.stackoverflow.com"]; [[self webView] loadRequest:[NSURLRequest requestWithURL:stackOverflowAddress]]; 

This can include the file you just wrote:

NSURL *htmlURL = [NSURL fileURLWithPath:htmlPath]; [[self webView] loadRequest:[NSURLRequest requestWithURL:htmlURL]]; 

Or, you can put a string into it directly:

[[self webView] loadHTMLString:htmlContent baseURL:nil]; 

If you use a UIWebView for a lot of your functionality, take the time to read the UIWebViewDelegate Protocol Reference.

Opening HTML in Safari

It is also possible to tell your application to open URLs elsewhere. This will usually result in Safari opening. However, because Safari does not have access to your app’s document directory, it cannot display documents while they are saved locally.

[[UIApplication sharedApplication] openURL:stackoverflowAddress]; 

Источник

Objective-C в вебе: вид со стороны сервера

На этот раз тема ObjC мной затронута на серверной стороне. К сожалению конкретики меньше, больше философии, но, надеюсь, кто-то найдет этот очерк интересным.

И так, в чем смысл примерения Objective-C со стороны сервера, есть ли он вообще и какие преимущества он дает.

С точки зрения скорости работы (тут и далее замеры подтверждены только apache benchmark, и могут не отображать всей сути вещей) Objective-C отстает от полностю компилированного кода на C++, но обходит Python (в лице Django) и PHP. Обходит в синтетическом тесте ab, где реально замеряется только скорость отдачи некешированного материала, так что your mileage may vary.

С другой стороны, веб-ориентированные языки (PHP), и веб-фреймворки (Django, Ruby on Rails) предоставляют разработчику широкий встроенный функционал по решению типичных для веба задач. С помощю того же Django можно достаточно быстро написать код для веб-системы с учетом стройной MVC-логики.

Посмотрим на этот вопрос еще со стороны прочего окружения сервера. Если в качестве ОС выступает OSX Server (на железе или виртуализированный), то в руки разработчика попадает рантайм с множеством готовых решений, вроде бы и для десктопа, но многие из них можно использовать и для серверных приложений. Например для хранения данных и ORM-доступа к ним можно использовать Core Data, для работы с любыми другими процессами (например отдельный comet-сервер, или даже удаленный OSX или iPhoneOS клиент) можно использовать Distributed Objects.

Конечно стоимость использования серверной OSX на несколько порядков выше, чем стоимость хостинга на Linux. «Дешево и сердито» на этой платформе будет достигать Cocotron. Степень покрытия API тут меньше, чем у Cocoa, но общий подход сохранен. А в недостающих местах помогут сторонние библиотеки, ведь ObjC отлично линкуется и с С и с С++. Гугловый CTemplate справится с выводом конечного результата, доступ к данным будет через SQLite Persistent Objects, или прямую линковку к mysql/pgsql. Все прелести динамического рантайма при этом остаются.

Некоторое время назад я уже пробовал сделать базовый веб-фреймворк для решения типичных задач на Objective-C. Прошло много времени с тех пор когда я написал первую строчку кода в этом направлении, и уже можно сделать какие-то выводы.

Писать простые веб-системы на ObjC — дорого (с точки зрения потраченного разработчиком времени). Заметный выигрыш достигается только в скорости работы и потребляемой ОП (на OpenVZ например несколько django-процессов и mysql вместе могут скушать все, дергая OOM по чем зря).

Интересные результаты получаются при написании общих систем для iPhone и веба. Тогда возрастает повторная используемость кода, можно сильно экономить на задачах передачи данных и синхронизации (например веб-система и парное к ней приложение под iPhone). Конечно можно сделать веб-приложение и для iPhone, c применением новых плюшек из HTML5, но у полноценной программы преимущество и в простоте разработки-отладки и в функциональном API.

Еще более интересные результаты — при использовании ObjC на сервере и rich-приложении Cappuccino на клиенте. Преимущества почти все те же, только код надо немного причесывать под objj-вид (с чем отлично справляется cpp — c preprocessor и несколько #define). Можно хранить одну и ту же объектную модель на сервере и веб-клиенте (а так же, потенциально — на desktop-клиентах).

Когда-нибудь ChromeOS будет единственной используемой, все данные будут в туче. А пока многие десктоп-приложения удобнее и функциональнее веб-аналогов, и некоторые задачи проще переносить из веб-интрефейса на десктоп. К примеру, несколько форумов IPB проще модерировать через нативный OSX-клиент, который оперативно может просмотреть необходимые ветки, сделать автомодерацию по ключевым словам, и будет экономно потреблять ОП. Tidy, libxml и libxslt — все представлены в Cocoa, и позволяют писать адаптированные десктоп-варианты сайтов с минимумом затрат. А использование общей логики для сервера и клиента во многих случаях удобно, что может оправдать использование Objective-C и со стороны сервера.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

An objective c wrapper around libxml for parsing HTML

timonus/Objective-C-HTML-Parser

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README

1. Open Your project in XCode and drag and drop all .h & .m Files into an appropriate folder 2. In the project settings add "/usr/include/libxml2" to the "header search paths" field 3. Ctrl Click the Frameworks group choose Add -> Existing Frameworks and from the list choose libxml2.dylib

About

An objective c wrapper around libxml for parsing HTML

Источник

Using the Document Object Model from Objective-C

The Document Object Model API implements the Level 2 Document Object Model (DOM) specification, developed by the World Wide Web Consortium. This specification provides a platform and language-neutral interface that allows programs and scripts to dynamically access and change the content, structure and style of a document —usually HTML or XML—by providing a structured set of objects that correspond to the document’s elements.

The intention of the DOM Objective-C API is to conform to—as close as technically possible—the W3C DOM specification. Therefore, standard Cocoa conventions such as method naming, argument titling, and exception handling may not be reflected in this API. Following a few conventions discussed in this article, you can derive the DOM Objective-C API from the specification. This article also discusses the differences between the DOM specification and DOM Objective-C API.

WebKit extensions to the DOM specification are covered in Using the Document Object Model Extensions . Refer to WebKit DOM Programming Topics for more information on the DOM specification.

Interpreting the DOM Specification

The DOM specification is written in Interface Definition Language (IDL) files available at the W3C web site. Links to them have been provided in the list that follows. The Objective-C DOM API is defined by header files in the WebKit framework, located at: /System/Library/Frameworks/WebKit.framework . Here is a list of the DOM specification’s IDL files and their associated Objective-C header files:

Two other header files are included in the Document Object Model API. DOM.h is a convenience header file that merely includes all of the other DOM header files. DOMExtensions.h defines additions that are not specified by the DOM specification. Use the extensions to help your DOM methods interact with the rest of WebKit, and to use some of WebKit’s higher abilities such as HTML editing. More information is available in the Using the Document Object Model Extensions article.

The interfaces specified by the DOM IDL files are mapped to Objective-C classes. The names of interfaces are unchanged when the specification does not conflict with the namespaces of Objective-C, Java, or other common languages. For example, the DOMImplementation interface in the DOM Core IDL is reflected by the same name in the Objective-C DOMCore header file. Where namespaces conflict, the API prefixes the conflicting interface appropriately. For example, the DOM Core IDL’s Node interface appears as DOMNode in its Objective-C mapping.

This naming scheme also extends to constants. The API groups DOM constant lists into Objective-C enum types, and if a namespace conflict is present, the API prefixes them with an appropriate identifier. For example, the ELEMENT_NODE node type constant is reflected as DOM_ELEMENT_NODE in Objective-C.

Some names specified by the DOM specification may conflict with keywords or other reserved words in Objective-C. When this happens, they are given custom mappings and their Objective-C names must be inferred from the headers or from documentation. The API provides the custom mappings with appropriate names. For example, the two conflicting identifiers id and name (both Objective-C reserved words) are mapped to idName and frameName , respectively, and accurately reflect the intent of the specification.

Each Objective-C class derives, directly or indirectly, from the DOM root object DOMObject . This is an implementation detail that accommodates cross traffic between WebKit and the DOM. The hierarchy of interfaces as defined by the W3C specification is also maintained. For example, DOMDocument extends from DOMNode in the specification as well as in the API.

Method names are mapped into Objective-C directly from the specification with no namespace transition. However, methods with multiple arguments in the DOM specification do not specify labels for their arguments—this behavior carries on into the Objective-C methods. For example, the specification declares this method prototype:

Node insertBefore(in Node newChild, in Node refChild);

The Objective-C version is not, as you might expect, changed to something like:

- (DOMNode *)insertNewChild:(DOMNode *)newChild
BeforeOld:(DOMNode *)refChild

Источник

Оцените статью