iOS Development Basics-Fragmentation 21

Source: Internet
Author: User
Tags starttls

iOS Development Basics-Fragmentation 21

1:[uiscreen Mainscreen].scale Knowledge points

When the screen is 640x940 [[UIScreen Mainscreen] scale]=2.0 when the screen is 320x480 respectively [[UIScreen Mainscreen] scale]=1.0

2: How to draw 1-pixel line correctly

#define Single_line_width           (1/[UIScreen mainscreen].scale) #define Single_line_adjust_offset   ((1/[UIScreen Mainscreen].scale)/2) code as follows: UIView *view = [[UIView alloc] Initwithframe:cgrect (x-single_line_adjust_offset, 0, Single_ Line_width, 100)]; Note: If the line width is even point, do not set the offset, or the line will be distorted

3:socket Programming-Asyncsocket

The standard recommendation of the iphone is that the Cfnetwork library is programmed with a packaged open source library, which is the Cocoa Asyncsocket Library, which simplifies cfnetwork invocation, providing the main features of asynchronous operations: non-blocking reads and writes of the queue, and optional timeouts. You can call it to read and write, and it will tell you automatically when the socket is received after completion. If you call it to receive a connection, it will start a new instance for each connection, and of course, you can turn off these connection delegation (delegate) support immediately. Error, connection, receive, full read, full write, progress, and disconnection can all be invoked through the delegate mode, rather than the thread, on the run loop. Although it can be used in the main thread or a worker thread, you do not need to do so. It invokes the delegate method asynchronously, using Nsrunloop. The delegate method, which includes the parameters of the socket, allows you to differentiate among multiple instances from being included in a class.            You do not need to operate the stream or socket, this class helps you to do all the supporting TCP streams based on IPV4 and IPV6 join: AsynSocket.h. M and AsynUdpSocket.h. m four files and cfnetwork.framework TCP client #import "AsyncSocket.h" @interface Helloiphoneviewcontroller:uiviewcontroller {uite                Xtfield * TextField;             Asyncsocket * Asyncsocket;             } @property (Retain, nonatomic) Iboutlet Uitextfield *textfield;             -(Ibaction) buttonpressed: (ID) sender;                 -(Ibaction) textfielddoneediting: (ID) sender; @end Use the Connecttohost join server where you need to join the Initwithdelegate parameter in which self is required. The function of each socket response in this object pointer will be AsyncsockeT is called. Initwithdelegate the current object is passed in so as to implement the corresponding method in the current object method asyncsocket = [[Asyncsocket alloc] initwithdelegate:self]                ;                Nserror *err = nil; if (![                  Asyncsocket connecttohost:host On:port Error:&err]) {NSLog (@ "error:%@", err); The NSData object is used for the NSData object regardless of whether the socket is sent or received. It's defined as Http://developer.apple.com/library/mac. /#documentation/cocoa/reference/foundation/classes/nsdata_class/reference/reference.html NSData is mainly with one (ID) data              The data space and length of the point.              NSString converted to NSData object nsdata* xmlData = [@ "testdata" datausingencoding:nsutf8stringencoding];               NSData converted to NSString object NSData * data;                NSString *result = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; Send data Asyncsocket WriteData method to send data, it has the following definition-(void) WriteData: (NSData *) data withtimeout: (Nstimeinterv AL) TimeOut tag: (long) tag;               The following is an instance statement.              nsdata* adata= [@ "test data" datausingencoding:nsutf8stringencoding];              [Sock Writedata:adata Withtimeout:-1 Tag:1];              In the Onsocket overload function, as defined by the send data that is specifically used to handle the socket:-(void) onsocket (Asyncsocket *) sock Didwritedatawithtag: (long) tag     {NSLog (@ "thread (%), onsocket:%p didwritedatawithtag:%d", [[Nsthread CurrentThread] name],               Sock,tag);               } receives the socket data.               In the Onsocket overload function, as defined by the receive data that is specifically used to handle the socket.    -(void) Onsocket: (Asyncsocket *) sock didreaddata: (NSData *) data withtag: (long) tag is converted to NSString in the middle to display.     nsstring* aStr = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];     NSLog (@ "===%@", aStr);      [ASTR release]; 6, the TCP connection reads the length of the data socket connection, may read a fixed length of bytes [socket ReadDataToLength:withTimeout:tag] The resolution of each Method-(void) Onsocket: (Asyncsocket *) sock WilldisconnectwitherroR: (Nserror *) err; An error occurred, the socket closed, you can call "Unreaddata" in the Call-back procedure to obtain the socket's last data byte, when connected, the delegate method in Onsocket:didacceptnewsocket: or      Onsocket:didconnecttohost: Previously called-(void) Onsocketdiddisconnect: (Asyncsocket *) sock; When the socket is disconnected due to or without errors, if you want to release the socket after disconnecting, this method works, while the Onsocket:willdisconnectwitherror release is unsafe-(void) Onsocket: (        Asyncsocket *) sock didacceptnewsocket: (Asyncsocket *) Newsocket; When a socket is generated to handle a connection call, this method returns the new socket on the thread run-loop and the delegate it should process, and if omitted, uses [Nsrunloop Cunrrentrunloop]-(BOOL) Onsocketwill       Connect: (Asyncsocket *) sock;          -(void) Onsocket: (Asyncsocket *) sock Didconnecttohost:(NSString *) host port: (UINt16) port; When the socket connection is ready to be read and write, the host property is an IP address, not a DNS name-(void) Onsocket: (Asyncsocket *) sock didreaddata: (NSData *) data with         Tag: (long) tag; Called when the required data is read into memory when the socket has completed, and if there is an error, do not call-(void) Onsocket: (Asyncsocket *) sock didreadpartialdataoflength: (Nsuinteger) part           Ialength tag: (long) tag; When a socket reads data but has not yet completed the read operation, theWith, if using Readtodata:or readtolength: Method will occur, can be used to update the progress bar and other things-(void) Onsocket: (Asyncsocket *) sock Didwritedatawithta             G: (long) tag; Called when a socket has finished writing request data (void) Onsocket: (Asyncsocket *) sock didwritepartialdataoflength: (Nsuinteger) Partialleng             Th tag: (long) tag; When a socket writes some data, but has not completed the entire write call, it can be used to update the progress bar and other things-(Nstimeinterval) Onsocket: (Asyncsocket *) sock SHOULDTIMEOUTREADW Ithtag: (long) tag elapsed: (Nstimeinterval) exapsed Bytesdone: (nsuinteger) length is called when the read operation has timed out but not yet completed, this method allows the discretionary delay timeout if Returns a positive time interval, the read timeout will have a certain amount of expansion, if this method is not implemented, or will return a negative time interval as usual, the elapsed parameter is the sum of the original timeout, plus any previous additions by this method, the length parameter is Read the number of bytes read so far, note that this method may be called multiple times by a single read-(Nstimeinterval) Onsocket: (Asyncsocket *) sock SHOULDTIMEOUTW                Ritewithtag: (long) tag elapsed: (nstimeinterval) Elapsed Bytesdone: (nsuinteger) length;               If a write operation has reached its timeout but has not yet completed, the call is as above-(void) Onsocketdidsecure: (Asyncsocket *) sock; Called when the socket successfully completes the SSL/TLS negotiation, this method unless you use the provide StArttls method is called, if SSL/TLS is an invalid certificate, the socket will be closed immediately, Onsocket:willdisconnectwitherror: The proxy method should be called with a specific SSL error code-(BOOL Cansafelysetdelegate is used to see if there is a pending business (read/write) with the current delegate before changing it. Of course, you should change the delegate before a secure connection or accept the delegate once the receive or join method is called, the Asyncsocket instance is locked, and the other receive/Connect methods are not disconnected before the socket is not called if the attempt fails or times out, these methods are Return no either call Onsocket:willdisconnectwitherror: or Onsockeddiddisconnect when the incoming connection is accepted, Asyncsocket calls multiple delegate methods.                 These methods are arranged in chronological order: 1.onsocket:didacceptnewsocket:2.onsocket:wantsrunloopfornewsocket: 3. Onsocketwillconnect: Your server code will need to retain a recognized socket (if you want to accept it), the best place to do this may be in Onsocket:didacce Ptnewsocket: The method in the read and write stream has been set for the newly accepted socket, the OnSocket:didConnectToHost:port method will invoke multithreading in the appropriate run loop, if you want to pass the actual Onsocket:wantsrunloopfornewsocket:, move another newly received socket to go to the other loop of the socket. Then, you should wait until the OnSocket:didConnectToHost:port: method before calling the read and write or STARTTLS methods. Otherwise the read and write time is originally due to the incorrect runloop, and chaos will occur-(BOOL) Acceptonport: (UInit16) Port ErroR: (Nserror *) errptr; Tells the socket to start listening and accepting connections on the specified port, and when a connection arrives, the Asyncsocket instance invokes various delegate methods, and the socket listens to all available interfaces (WiFi, Ethernet, etc.)-(BOOL) Connecttohost: (NS             String *) hostname onPort: (UInt16) Port Error:(nserror * *) errptr;             Connect a given host and port, host hostname can be a domain name or IP address-(BOOL) connecttoaddress: (NSData *) remoteaddr Error: (Nserror *) errptr; Connect to a given address, specify a SOCKADDR structure that wraps a NSData object, for example, NSData object is returned from the Nsnetservice address method, and if there is an existing SOCKADDR structure, you can convert it to a NSData object, Like this: struct sockaddr sa, nsdata *dsa = [NSData datawithbytes:&remoteaddr Length:remoteAddr.sa_len];             struct sockaddr *sa, nsdata *DSA = [NSData datawithbytes:remoteaddr length:remoteaddr->sa_len];                -(void) disconnect; Immediately disconnects, any unread read or write will be discarded if the socket has not been disconnected, the Onsocketdiddisconnect delegate method will be immediately invoked before the method returns, and the recommended release ASYNCSO                   Cket instances: [Asyncsocket setdelegate:nil];                   [Asyncsocket disconnect];     [Asyncsocket release];         -(void) disconnectafterreading;              After all the pending reads have been completed, the read and write methods will be useless after the call, and the socket will be disconnected even if there is still something written-(NSString *) connectedhost;              -(UInt16) Connectedport;              -(NSString *) localHost;                -(UInt16) LocalPort; Returns the local and remote host and port to the connected socket, if no connection will return nil or 0, the host will be an IP address-(NSData *) connectedaddress-(NSData *) localaddr                ESSS returns the local and remote address to the connected socket, specifying a SOCKETADDR structure wrapped in a NSData object ReadData and WriteData methods will not be blocks (they are asynchronous)               Called when the read completion OnSocket:didReadData:withTag: Delegate method is invoked when the write-complete Onsocket:didwritedatawithtag: Delegate method is called You can select the timeout setting for any read/write operation (in order to not time out, use a negative time interval. If the read/write operation times out, the corresponding onsocket:shouldtimeout ... The delegate method is called to selectively allow us to extend the timeout timeout after the Onsocket:willdisconnectwitherror: method is called, followed by Onsocketdiddisconnect t              AG is for convenience, it can be used as an array of indexes, steps, state ID, pointers, etc.-(void) Readdatawithtimeout: (nstimeinterval) tiemout tag: (long) tag; Read the socket on the firstThe byte that becomes available at one time, if the timeout value is negative, the read operation will not use timeout-(void) Readdatawithtimeout: (nstimeinterval) Timeout buffer: (Nsmutableda              TA *) buffer bufferoffset: (nsuinterger) offset tag: (long) tag; A byte byte that becomes available on the first read socket will be appended to the given byte buffer, starting at the given offset, if required, the given buffer size will automatically increase if the timeout value is negative, read Do not use timeout if the buffer is empty, the socket creates a buffer for us if Bufferoffset is greater than the given buffer length, the method will be useless and the delegate will not be called as If you pass a buffer, and you cannot change it in any way when Asyncsocket is using it, the data returned by ONSOCKET:DIDREADDATA:WITHTAG will be a subset of a given buffer It is said that it will be referenced to the byte of the given buffer being appended-(void) Readdatatolength: (nsuinterger) Length withtimeout: (nstimeinterval) timeout tag: (lo            NG) tag; Reads the given number of bytes, if length is 0, the method will be useless and the delegate will not be called-(void) Readdatatolength: (nsuinteger) Length withtimeout: (nstimeinterval) Tiemo            UT buffer: (nsmutabledata *) buffer bufferoffset: (nsuinteger) offset tag: (long) tag; Reads the given number of bytes, starting at the given offset, the byte is appended to the given byte buffer-(void) Readdatatodata: (NSData *) Data WIthtimeout: (nstimeinterval) timeout tag: (long) tag; Reads the byte until (including) the passed as delimited "data" parameter if passing 0 or 0 of the length, the "data" parameter, the method will be useless, the delegate will not be called to read a row from the socket, using the "data" parameter as the delimiter of the row (such as HT TP CRLF) Note that this method is not a character set, so if a delimiter appears, it can naturally act as part of the encoding, and the read will end prematurely-(void) Readdatatodata: (NSData *) data witht           Imeout: (nstimeinterval) Timeout buffer: (nsmutabledata *) buffer bufferoffset: (nsuinteger) offset tag: (long) tag;           Reads the byte until (including) the passed-in as a delimited "data" parameter, at the beginning of the given offset, the byte is appended to the given byte buffer. Reads a row from the socket, using the "data" parameter as the delimiter for the row (for example, CRLF of HTTP)-(void) WriteData: (NSData *) data withtimeout: (nstimeinterval) Timeout T          AG: (long) tag; Writes data to the socket when the delegate is called-(float) Progressofreadreturningtag: (long *) tag bytesdone: (Nsuinteger *) done total: (N           Suinteger *) Total;           -(float) Progressofwritereturningtag: (long *) tag bytesdone: (Nsuinteger *) Done: (Nsuinteger *) total;                Returns the current read or write progress, from 0.0 to 1.0 or if there is no read/write return Nan (using isNaN to check) tag, done, and total if not empty, they will be filled      -(void) StartTLS: (Nsdictionary *) tlssettings; Make sure to use SSL/TLS connection This method can be called at any time, and the TLS handshake will occur after all outstanding read/write finishes. This is followed by a protocol option that sends dependent STARTTLS messages, at the same time that the queue is escalated to TLS without having to wait for the write to complete.              After this method is called, any read-write plan will occur on the secure link for possible keys and the value of TLS settings is well documented some possible keys are: *-kcfstreamssllevel *-Kcfstreamsslallowsexpiredcertificates *-kcfstreamsslallowsexpiredroots *-KCFSTR              Eamsslallowsanyroot *-Kcfstreamsslvalidatescertificatechain *-Kcfstreamsslpeername *-Kcfstreamsslcertificates *-kcfstreamsslisserver If you pass an empty or empty dictionary, the default dictionary default setting will be checked to ensure           By signing a trusted third-party Certificate authority and a certificate that does not have an expired remote connection However, it does not validate the name on the certificate, unless you give it a name, by Kcfstreamsslpeername key to verify that the impact on security is important to understand Imagine that you are trying to create a secure connection to mysecureserver.com, but because of an attack on the DNS server, so your socket is directed to maliciousserver.com if you just use the default settings, Maliciousser Ver.com has a valid certificate default setting will not be able to monitor any issues because the certificate is valid in this particular case, to properly protect your connection, you should set the KcfstreamsslThe PeerName property is mysecureserver.com. If you do not know the name of the remote host in advance (for example, you do not confirm that it is domain.com "or" www.domain.com "), then you can use the default settings to verify the certificate and then Verify that the X509Certificate class is used after the release to verify that the X509Certificate class is part of the Cocoaasyncsocket Open source project-(void) enableprebuffering for handling Readd Atatodata request, data is the performance that must be read from the socket in small increments by allowing Asyncsocket to read chunks of data at once and store any small internal buffer overflow thing to greatly improve this is called pre-buffering, as if some data in your Ask for it before it could be read out if you often use Readdatatodata, using pre-buffering will have better performance, especially on the iphone the default pre-buffering state is controlled by the default_prebuffering definition, and it is strongly recommended to set it to          Yes this method exists where some pre-buffering is required for some unforeseen reasons that are disabled by default, when this method exists allows the pre-buffering-(BOOL) Movetorunloop: (Nsrunloop *) to be easily enabled when it is ready to runloop; When you create a asyncsocket, it is added to the current thread runloop for a manually created socket, on the thread you intend to use it, it is easiest to simply create the socket on the threads when a new socket is accepted, The delegate method Onsocket:wantsrunloopfornewsocket will be called to allow you to place the socket on a separate thread, which is best combined in the same thread pool design if, however, on a separate thread, at a later time, you need to move a Socket, this method can be used to complete a task this method must be/runloop from the currently running thread of the socket call Note: After this method call, all further methods should be raised from the given runloop with this object   , all delegate calls will be sent to the given Runloop       -(BOOL) Setrunloopmodes: (Nsarray *) runloopmodes;          -(BOOL) Addrunloopmode: (NSString *) Runloopmode;           -(BOOL) Removerunloopmode: (NSString *) Runloopmode; Allows you to configure the socket using the run loop mode run cycle Mode setting default is Nsrunloopcommonmodes if you want your socket to continue operating in other modes, you may need to add a pattern nsmodalpanel           Runloopmode or Nseventtrackingrunloopmode, or you might just want to use the nsrunloopcommonmodes acceptable socket will automatically inherit the same running loop mode as listening to the socket Note: Nsrunloopcommonmodes is defined in 10.5, and for previous versions you can use Kcfrunloopcommonmodes-(Nsarray *) Runloopmodes to return the current         The Asyncsocket instance of the running loop mode, the default setting for Run loop modes is Nsdefaultrunloopmode-(NSData *) Unreaddata;   An error event in Onsocket:willdisconnectwitherror: will be called to read any data left on the socket + (NSData *) Crlfdata;     0x0D0A + (NSData *) Crdata;     0x0D + (NSData *) Lfdata;   0x0A + (NSData *) Zerodata;  0x00 Some common delimiters, in order to go to use Readdatatodata:. Method

Basics of iOS development-fragmentation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.