HTML52012. 6. 12. 09:04


출처: http://croute.me/419


Web Storage란?
웹 스토리지란 클라이언트쪽에 소량의 데이터를 저장해 두기 위한 스토리지입니다.


웹 스토리지를 다룰때는 그동안 일반적으로 사용되던 쿠키와 많이 비교를 하게 되는데요, 
간단하게 한번 보도록 하겠습니다.

쿠키

 4KB의 저장 용량, 크기가 작다. 
 같은 사이트내에서 둘 이상의 탭을 열었을 때, 둘 이상의 트랜젝션 추적에 어려움이 있다.
 이 외에도 여러 보안문제가 있다. 
 
웹 스토리지
 사양에 따르면 크기 제한이 없다.
 서버로 보내지 않는다.(원하면 명시적으로 보낼 수 있다.)
 유효기간이 없다.
 JavaScript 객체를 저장할 수 있다.(정확하게는 객체의 복사본이 저장된다.)
 웹 스토리지에는 Session Storage와 Local Storage가 있다.



 키와 값

Web Storage는 간단하게 키와 값으로 데이터를 저장할 수 있습니다.
또한 해당하는 키를 통해 값을 꺼낼 수 있습니다.





 웹 스토리지의 유효 범위

웹 스토리지의 유효범위는 Session Storage와 Local Storage에 약간 차이가 있습니다.
먼저 그림으로 살펴보고 아래의 내용을 읽어보면 쉽게 이해할 수 있습니다.


Session Storage
- 도메인마다 따로 생성된다.
- 윈도우(window 객체)와 같은 유효범위와 생존기간을 가진다. (같은 도메인이라도 윈도우마다 따로 생성된다.)
- 윈도우 복제로 생성된 경우, 스크립트를 이용해 새 창을 연 경우 같은 값을 가진 세션 스토리지가 "복제"된다.
- 새로 생성된 윈도우와 기존 윈도우의 세션 스토리지는 서로 영향을 주지 않는다.

Local Storage
- 도메인마다 따로 생성된다.
- 지속기간에 제한이 없다. 사용자가 명시적으로 지우지 않는 한 영구적으로 저장된다.
- 도메인이 다르면 서로의 로컬 스토리지에 접근할 수 없다. (hi.croute.me와 hello.croute.me는 다른 로컬 스토리지)
- 같은 도메인, 예를들면 croute.me에 소속된 웹페이지는 모두 같은 로컬 스토리지를 가진다.(접근한다.)
- Cookie를 이용한 사이트 고유 설정 정보등을 대신하기에 적당하다.

세션과 로컬의 차이점은 로컬은 지속성(보존)을 가지기 때문에 여러 창을 켜도 같은 도메인이라면, 같은 스토리지를 사용하는 것입니다.
세션 스토리지는 각 세션마다 새로운 스토리지를 사용하고 폐기합니다.




 웹 스토리지 메소드

스토리지의 메소드는 세션 스토리지와 로컬 스토리지의 메소드가 같습니다.

 메소드 설명
 length 스토리지에 저장된 데이터의 수를 반환
 key(index) 지정된 인덱스의 키를 반환하고 키가 없다면 null 반환
 getItem(key) 지정된 키에 대응하는 데이터를 반환
 setItem(key, data) 지정된 키로 스토리지에 데이터를 저장
 removeItem(key) 지정된 키에 대응하는 데이터를 삭제
 clear() 모든 데이터를 스토리지에서 삭제


아래는 로컬 스토리지를 통해 알아본 저장/읽기/삭제에 대한 사용 예입니다.
메소드를 통하지 않은 키를 통한 직접적인 접근도 할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 저장
localStorage.croute = "good job";
localStorage["croute"] = "good job";
localStorage.setItem("croute", "good job");
 
// 읽기
var croute = localStorage.croute;
var croute = localStorage["croute"];
var croute = localStorage.getItem["croute"];
 
// 삭제
delete localStorage.croute;
delete localStorage["croute"];
localStorage.removeItem("croute");



아래는 for loop를 사용해서 storage에 저장된 모든 값을 가져오는 코드입니다.

1
2
3
4
5
for(var i = 0; i < localStorage.length; i++)
{
    var key = localStorage.key(i);
    var value = localStorage[key];
}




아래는 웹 스토리지(Web Storage)를 공부하며 참고, 작성한 코드입니다.(HTML5&API 입문 Chap.12)
세션 스토리지 예제 코드


로컬 스토리지 예제 코드


로컬 스토리지(eventListener를 사용한) 예제 코드



local_storage_addEventListener.html 같은 경우에는 제대로 실행되지 않습니다.

Posted by 삼스
iOS2012. 3. 24. 13:37


URL Loading System Error Codes

NSURLErrorDomain에서 정의하는 NSError의 에러코드들은 아래와 같다.
enum

{
NSURLErrorUnknown = -1,
NSURLErrorCancelled = -999,
NSURLErrorBadURL = -1000,
NSURLErrorTimedOut = -1001,
NSURLErrorUnsupportedURL = -1002,
NSURLErrorCannotFindHost = -1003,
NSURLErrorCannotConnectToHost = -1004,
NSURLErrorDataLengthExceedsMaximum = -1103,
NSURLErrorNetworkConnectionLost = -1005,
NSURLErrorDNSLookupFailed = -1006,
NSURLErrorHTTPTooManyRedirects = -1007,
NSURLErrorResourceUnavailable = -1008,
NSURLErrorNotConnectedToInternet = -1009,
NSURLErrorRedirectToNonExistentLocation = -1010,
NSURLErrorBadServerResponse = -1011,
NSURLErrorUserCancelledAuthentication = -1012,
NSURLErrorUserAuthenticationRequired = -1013,
NSURLErrorZeroByteResource = -1014,
NSURLErrorCannotDecodeRawData = -1015,
NSURLErrorCannotDecodeContentData = -1016,
NSURLErrorCannotParseResponse = -1017,
NSURLErrorInternationalRoamingOff = -1018,
NSURLErrorCallIsActive = -1019,
NSURLErrorDataNotAllowed = -1020,
NSURLErrorRequestBodyStreamExhausted = -1021,
NSURLErrorFileDoesNotExist = -1100,
NSURLErrorFileIsDirectory = -1101,
NSURLErrorNoPermissionsToReadFile = -1102,
NSURLErrorSecureConnectionFailed = -1200,
NSURLErrorServerCertificateHasBadDate = -1201,
NSURLErrorServerCertificateUntrusted = -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid = -1204,
NSURLErrorClientCertificateRejected = -1205,
NSURLErrorClientCertificateRequired = -1206,
NSURLErrorCannotLoadFromNetwork = -2000,
NSURLErrorCannotCreateFile = -3000,
NSURLErrorCannotOpenFile = -3001,
NSURLErrorCannotCloseFile = -3002,
NSURLErrorCannotWriteToFile = -3003,
NSURLErrorCannotRemoveFile = -3004,
NSURLErrorCannotMoveFile = -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete = -3007
}

엄청 많타!@ 


NSURLErrorUnknown

시스템에 정의되지 않은 에러. 이 에러가 나면 프레임웍이나 라이브러리의 문제로 애플에 보고해달란다.Available in Mac OS X v10.2 and later.


NSURLErrorCancelled

로드중에 취소하면 발생
NSURLConnection이나 NSURLDownload는 download가 취소된 경우에는 발생하지 않는다.
Available in Mac OS X v10.2 and later.


NSURLErrorBadURL

잘못된 URL  form으로 접근시도시 발생.
Available in Mac OS X v10.2 and later.


NSURLErrorTimedOut

페이지 로딩이 완료되기 전에 지정한 시간이 지나면 발생.

Available in Mac OS X v10.2 and later.


NSURLErrorUnsupportedURL

URL폼이 프레임웍에서 지원하지 않는 경우, 유효하지 않은 프로토콜입력시 발생 가능함.
Available in Mac OS X v10.2 and later.


NSURLErrorCannotFindHost

URL에서 지정하는  host name을 찾지 못한 경우
Available in Mac OS X v10.2 and later.


NSURLErrorCannotConnectToHost

호스트 연결이 실패한 경우. 호스트이름은 찾았는데 호스트가 다운되어 있거나 해당 포트에 연결 제한이 걸려 연결이 안된 경우에 발생 가능하다.

Available in Mac OS X v10.2 and later.


NSURLErrorDataLengthExceedsMaximum

요청단 데이터가 길이제한을 상회한 경우
Available in Mac OS X v10.5 and later.


NSURLErrorNetworkConnectionLost

서버와의 연결이 로드중에 문제가 발생한 경우

Available in Mac OS X v10.2 and later.


NSURLErrorDNSLookupFailed

See NSURLErrorCannotFindHost

Available in Mac OS X v10.2 and later.


NSURLErrorHTTPTooManyRedirects

redirection이 발생한 경우 또는 16회 이상이 발생한 경우

Available in Mac OS X v10.2 and later.


NSURLErrorResourceUnavailable

요청한 리소스를 찾을 수 없는 경우, 예: "file not found", data decoding error등

Available in Mac OS X v10.2 and later.


NSURLErrorNotConnectedToInternet

네트웍을 요청하였는데 인터넷연결이 안된경우, 자동연결시도가 실패한경우, 연결상태가 안좋은 경우, 또는 사용자가 네트웍연결을 자동으로 선택하지 안은 경우 발생

Available in Mac OS X v10.2 and later.


NSURLErrorRedirectToNonExistentLocation

서버에서 잘못된 redirect를 한경우
Available in Mac OS X v10.2 and later.


NSURLErrorBadServerResponse

서버로부터 잘못된 데이터를 수신한경우. "500 server error"에 대응된다.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorUserCancelledAuthentication

인증과정 중 사용자가 취소한 경우 발생. 

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorUserAuthenticationRequired

인증인 리소스에 접근이 필요할 때 발생
Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorZeroByteResource

Returned when a server reports that a URL has a non-zero content length, but terminates the network connection “gracefully” without sending any data.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorCannotDecodeRawData

Returned when content data received during an NSURLConnection request cannot be decoded for a known content encoding.

Available in Mac OS X v10.5 and later.

Declared in NSURLError.h.

NSURLErrorCannotDecodeContentData

Returned when content data received during an NSURLConnection request has an unknown content encoding.

Available in Mac OS X v10.5 and later.

Declared in NSURLError.h.

NSURLErrorCannotParseResponse

Returned when a response to an NSURLConnection request cannot be parsed.

Available in Mac OS X v10.5 and later.

Declared in NSURLError.h.

NSURLErrorInternationalRoamingOff

Returned when a connection would require activating a data context while roaming, but international roaming is disabled.

Available in Mac OS X v10.7 and later.

Declared in NSURLError.h.

NSURLErrorCallIsActive

Returned when a connection is attempted while a phone call is active on a network that does not support simultaneous phone and data communication (EDGE or GPRS).

Available in Mac OS X v10.7 and later.

Declared in NSURLError.h.

NSURLErrorDataNotAllowed

Returned when the cellular network disallows a connection.

Available in Mac OS X v10.7 and later.

Declared in NSURLError.h.

NSURLErrorRequestBodyStreamExhausted

Returned when a body stream is needed but the client does not provide one. This impacts clients on iOS that send a POST request using a body stream but do not implement the NSURLConnection delegate method connection:needNewBodyStream.

Available in Mac OS X v10.7 and later.

Declared in NSURLError.h.

NSURLErrorFileDoesNotExist

Returned when a file does not exist.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorFileIsDirectory

Returned when a request for an FTP file results in the server responding that the file is not a plain file, but a directory.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorNoPermissionsToReadFile

Returned when a resource cannot be read due to insufficient permissions.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorSecureConnectionFailed

Returned when an attempt to establish a secure connection fails for reasons which cannot be expressed more specifically.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorServerCertificateHasBadDate

Returned when a server certificate has a date which indicates it has expired, or is not yet valid.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorServerCertificateUntrusted

Returned when a server certificate is signed by a root server which is not trusted.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorServerCertificateHasUnknownRoot

Returned when a server certificate is not signed by any root server.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorServerCertificateNotYetValid

Returned when a server certificate is not yet valid.

Available in Mac OS X v10.4 and later.

Declared in NSURLError.h.

NSURLErrorClientCertificateRejected

Returned when a server certificate is rejected.

Available in Mac OS X v10.4 and later.

Declared in NSURLError.h.

NSURLErrorClientCertificateRequired

Returned when a client certificate is required to authenticate an SSL connection during an NSURLConnection request.

Available in Mac OS X v10.6 and later.

Declared in NSURLError.h.

NSURLErrorCannotLoadFromNetwork

Returned when a specific request to load an item only from the cache cannot be satisfied.

This error is sent at the point when the library would go to the network accept for the fact that is has been blocked from doing so by the “load only from cache” directive.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorCannotCreateFile

Returned when NSURLDownload object was unable to create the downloaded file on disk due to a I/O failure.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorCannotOpenFile

Returned when NSURLDownload was unable to open the downloaded file on disk.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorCannotCloseFile

Returned when NSURLDownload was unable to close the downloaded file on disk.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorCannotWriteToFile

Returned when NSURLDownload was unable to write to the downloaded file on disk.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorCannotRemoveFile

Returned when NSURLDownload was unable to remove a downloaded file from disk.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorCannotMoveFile

Returned when NSURLDownload was unable to move a downloaded file on disk.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorDownloadDecodingFailedMidStream

Returned when NSURLDownload failed to decode an encoded file during the download.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

NSURLErrorDownloadDecodingFailedToComplete

Returned when NSURLDownload failed to decode an encoded file after downloading.

Available in Mac OS X v10.2 and later.

Declared in NSURLError.h.

Availability
  • Available in Mac OS X v10.2 with Safari 1.0 installed.
  • Available in Mac OS X v10.2.7 and later.
Declared In
NSURLError.h

Posted by 삼스
iOS2012. 3. 10. 22:13

출처: http://peepleware.com/home/?mid=Tips_dev&page=3&document_srl=12071

아이폰에서 UIWebView 는 PDF 파일외 MS OFFICE계열의 문서 뷰어, 이미지 파일 뷰어, 음악/동영상 파일 열기 등의 다용도 뷰어로 활용할 수 있습니다.


다만 단점이라면 파일 로딩시 파일을 모조리 다 읽어 들여 큰 파일의 경우 메모리 부족 현상이 올 수 있습니다.

그래서 UIWebView로 여러개의 파일들을 지속적으로 반복해서 읽게 되는 경우 메모리 부족으로 인해 UIViewController의 didReceiveMemoryWarning 메소드가 호출될 때가 많아집니다.


그래서 몇 가지 처리를 통해 약간이나마 메모리 부족 현상을 개선해봤습니다.


우선 앱의 초기화 루틴에서 다음과 같이 처리합니다.


- (void)applicationDidBecomeActive:(UIApplication *)application {

    /*

     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

     */


// UIWebView에서 사용될 내부 캐시 영역을 만듭니다. 

// 내부 메모리/디스크를 사용하지 않도록 설정했습니다.

// 설정된 캐시 영역을 공통으로 사용하도록 설정합니다.


// 이 부분의 개선을 통해 더욱 발전시킬 여지가 있습니다.

// 점점 개선한 루틴을 통해 실험해보고, 효과가 있으면 소스를 변경하겠습니다.


NSURLCache *sharedCache = [[NSURLCache allocinitWithMemoryCapacity:0 diskCapacity:0 diskPath:nil]; 

[NSURLCache setSharedURLCache:sharedCache]; 

[sharedCache release];

// 그외 다른 초기 작업들.

}


UIWebView 에서 파일을 열고 사용하다 필요가 없어졌을 때, 호출할 함수.


- (void)unload

{


// 다른 자원들의 해제 작업들.


// UIWebView에서 사용된 요청들의 결과들 캐시를 삭제합니다.

// 이때 대상 캐시는 앱의 초기 구동시에 만들어둔 바로 그 캐시 영역입니다.


NSURLCache *sharedCache = [NSURLCache sharedURLCache]; 

[sharedCache removeAllCachedResponses];

return;

}


그래도 메모리 부족이 발생했을 때 사용할 메소드.


- (void)didReceiveMemoryWarning 

{

    // Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

    

    // Release any cached data, images, etc. that aren't in use.

NSURLCache *sharedCache = [NSURLCache sharedURLCache]; 

[sharedCache removeAllCachedResponses];

}


우선 이렇게 처리했을 때 메모리 부족 현상이 줄어들었고, Instruments - Allocations 로 메모리 사용 현황을 추적해보니 어느 정도 자원의 해제가 잘 되고 있었습니다.

Posted by 삼스