Basic knowledge of IOS development-fragment 21, basic knowledge of ios-Fragment
1: [UIScreen mainScreen]. scale knowledge point
When the screen is 640x940, [[UIScreen mainScreen] scale] = 2.0 when the screen is 320xlarge, [[UIScreen mainScreen] scale] = 1.0
2: How to correctly draw a line of 1 pixel
# Define SINGLE_LINE_WIDTH (1/[UIScreen mainScreen]. scale) # define SINGLE_LINE_ADJUST_OFFSET (1/[UIScreen mainScreen]. scale)/2) code: UIView * view = [[UIView alloc] initWithFrame: CGrect (x-SINGLE_LINE_ADJUST_OFFSET, 0, SINGLE_LINE_WIDTH, 100)]; note: if the line width is an even Point, do not set the offset; otherwise, the line will be distorted.
3: socket programming-Asyncsocket
The standard recommendation for Iphone is CFNetwork library programming. The encapsulated open-source library is cocoa AsyncSocket library, which can be used to simplify CFNetwork calls. It provides the following asynchronous operations: non-blocking read and write of the queue, and optional timeout. You can call it to read and write data. It will notify you of automatic socket reception after completion. If you call it to receive connections, it will start a new instance for each connection. Of course, you can also immediately close the support for these connection delegation (delegate. Errors, connections, reception, complete reading, complete writing, progress, and disconnection can all be called Based on the run loop through the delegate mode, rather than the thread. Although it can be used in the main thread or working thread, you do not need to do so. It calls the delegate method asynchronously and uses the nsunloop. The delegate method includes socket parameters, allowing you to differentiate itself from the same class in multiple instances. You do not need to operate the stream or socket. This class helps you to add all TCP streams based on IPV4 and IPV6: AsynSocket. h. m and AsynUdpSocket. h. four files and CFNetwork. framework TCP client # import "AsyncSocket. h "@ interface comment: UIViewController {UITextField * textField; AsyncSocket * asyncSocket;} @ property (retain, nonatomic) IBOutlet UITextField * textField;-(IBAction) buttonPressed: (id) sender; -(IBAction) textFieldDoneEditing: (id) sender; @ e Nd uses connectToHost to connect to the server where the connection is required. In the initWithDelegate parameter, self is required. The Socket response functions in this object pointer will be called by ASyncSocket. initWithDelegate transfers the current object, so that you only need to implement the corresponding asyncSocket = [AsyncSocket alloc] initWithDelegate: self] in the current object method; NSError * err = nil; if (! [AsyncSocket connectToHost: host on: port error: & err]) {NSLog (@ "Error: % @", err);} NSData objects use NSData objects regardless of SOCKET sending and receiving. it is defined as http://developer.apple.com/library/mac/# documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html NSData mainly with a (id) data pointing to the data space and length. NSString to NSData object NSData * xmlData = [@ "testdata" dataUsingEncoding: NSUTF8StringEncoding]; NSData to NSString Object NSData * data; NSString * result = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; The AsyncSocket writeData Method for sending data, as defined below-(void) writeData :( NSData *) data withTimeout :( NSTimeInterval) timeout tag :( long) tag; the following is an instance statement. NSData * aData = [@ "test data" dataUsingEncoding: NSUTF8StringEncoding]; [sock writeData: aData withTimeout:-1 tag: 1]; function overload in onSocket, for example, the definition is specifically used to process the data sent by the SOCKET :- (Void) onSocket (AsyncSocket *) sock didWriteDataWithTag :( long) tag {NSLog (@ "thread (%), onSocket: % p didWriteDataWithTag: % d ", [[NSThread currentThread] name], sock, tag);} receives Socket data. in the onSocket overload function, the definition is used to process the received data of the SOCKET. -(void) onSocket :( AsyncSocket *) sock didReadData :( NSData *) data withTag :( long) The tag is converted to NSString in the middle for display. NSString * aStr = [[NSString alloc] initWithData: data encoding: NSUTF8StringEnc Oding]; NSLog (@ "==%@", aStr); [aStr release]; 6. The TCP connection reads the data socket connection with a specified length, it is possible to read the Fixed Length byte [socket readDataToLength: withTimeout: tag] resolution of each method-(void) onSocket :( AsyncSocket *) sock willDisconnectWithError :( NSError *) err; error, when the socket is closed, you can call "unreadData" in the call-back process to obtain the last Data byte of the socket. During connection, the delegate method is either onSocket: didAcceptNewSocket: Or onSocket: didConnectToHost: previously called-(void) onSocketDidDisconnect :( ASyncSocket *) sock; when The socket is disconnected because there is no error. If you want to release the socket after the connection is disconnected, this method works, and releasing it in onSocket: willDisconnectWithError is not secure-(void) onSocket :( AsyncSocket *) sock didAcceptNewSocket :( AsyncSocket *) newSocket; called when a socket is generated to process the connection, this method will return the new socket of the run-loop on the thread and the Delegate to be processed. If omitted, use [nsunloop cunrrentRunLoop]-(BOOL) onSocketWillConnect :( AsyncSocket *) sock; -(void) onSocket :( AsyncSocket *) sock didConnectToHost :( NSString *) host port :( UINt16) Port; called when the socket connection is preparing to read and write, the host attribute is an IP address instead of a DNS name-(void) onSocket :( AsyncSocket *) sock didReadData :( NSData *) data withTag :( long) tag; called when the socket has completed the required data read into the memory, if there is an error, do not call-(void) onSocket :( Asyncsocket *) sock didReadPartialDataOfLength :( NSUInteger) partiaLength tag :( long) tag; called when a socket reads data but has not completed the read operation, if readToData: or readToLength: method is used, it can be used to update progress bars and other things-(void) onSocket :( AsyncSocket *) sock didWrit EDataWithTag :( long) tag; call-(void) onSocket :( AsyncSocket *) sock didWritePartialDataOfLength :( NSUInteger) partialLength tag :( long) when a socket has completed writing request data; 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 shouldTimeoutReadWithTag :( long) tag elapsed :( NSTimeInterval) exapsed bytesDone :( NSUInteger) length is called when the read operation has timed out but has not been completed. This method allows random delay timeout. If a positive interval is returned, the read timeout will be extended in a certain amount. This method may return a negative interval as usual. The elapsed parameter is the sum of the original timeout values, plus any supplement previously added using this method, the length parameter is the number of bytes read so far by the read operation. Note that if a positive number is returned, This method may be called multiple times by a separate read operation (NSTimeInterval) onSocket :( AsyncSocket *) sock shouldTimeoutWriteWithTag :( long) tag elapsed :( NSTimeInterval) elapsed bytesDone :( NSUInteger) length; if a write operation has reached its timeout but is not finished yet, same as above-(void) onSocketDidSecure :( AsyncSocket *) sock; called when the socket successfully completes ssl/tls negotiation. This method is called unless you use the startTLS method, if ssl/tls is invalid, The socket will be immediately closed, and the onSocket: willDisconnectWithError: proxy method will be called together with the specific ssl error code-(BOOL) canSafelySetDelegate to check before changing it, whether there is any pending business (read/write) with the current delegate ). Of course, the delegate should be changed before the secure connection or receipt of the Delegate. Once the receiving or connection method is called, The AsyncSocket instance will be locked, other receiving/connection methods are not called if the socket is not disconnected first. If the attempt fails or times out, these methods either return NO or 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's code will need to retain the accepted socket (if you want to accept it), the best thing is to do this possible in onSocket: didAcceptNewSocket: the method for reading and writing streams has been set for the new accepted socket. The onSocket: didConnectToHost: port method will call multiple threads in the appropriate running cycle. If you want to implement onSocket: wantsRunLoopForNewSocket :, move another received socket to another circular socket. Then, wait until onSocket: didConnectToHost: port: method before calling the read/write or startTLS method. Otherwise, the read and write time is originally set to an incorrect runloop, causing confusion-(BOOL) acceptOnPort :( UInit16) port error :( NSError **) errPtr; tell the socket to start listening to and accepting connections on the specified port. When a connection arrives, the AsyncSocket instance will call various delegate methods, and the socket will listen to all available interfaces (wifi, Ethernet, etc) -(BOOL) connectToHost :( NSString *) hostname onPort :( UInt16) port error :( NSError *) errPtr; connect to the specified 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 and specify a sockaddr structure to enclose an NSDa Ta object. For example, the NSData object is returned from the NSNetService address method. If an existing sockaddr structure exists, you can convert it to an NSData object, as shown in the following figure: 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; disconnect immediately, any unprocessed read or write operations will be discarded. If the socket is not disconnected, the onSocketDidDisconnect delegate method will be called immediately before this method is returned. Note the recommended method for releasing the AsyncSocket instance is as follows: [asyn CSocket setDelegate: nil]; [asyncSocket disconnect]; [asyncSocket release];-(void) disconnectAfterReading; disconnects when all pending reads have been completed. After the call, the read and write methods will be useless, and the socket will be disconnected even if something is still written-(NSString *) connectedHost;-(UInt16) connectedPort;-(NSString *) localHost;-(UInt16) localPort; return the local and remote host and port to connect to the socket, if there is no connection will return nil or 0, the host will be an IP address-(NSData *) connectedAddress-(NSData *) localAddresss returns the local and remote addresses to the connected socket and specifies a socketadd The r structure is wrapped in an NSData object. The readData and writeData methods are not blocks (they are asynchronous). When onSocket: didReadData: withTag: Is read complete, onSocket: didWriteDataWithTag is called: you can select any read/write operation timeout settings when calling a delegate method (to avoid timeout, use a negative 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 value after the onSocket: willDisconnectWithError: method is called, followed by the onSocketDidDisconnect tag for convenience, it can be used as an array index, step number, state id, pointer, etc.-(void) readDataWithTimeout :( NSTimeInterval) tiemout tag :( long) tag; read the first available byte on the socket, if the timeout value is negative, the read operation does not use timeout-(void) readDataWithTimeout :( NSTimeInterval) timeout buffer :( NSMutableData *) buffer bufferOffset :( NSUInterger) offs. Et tag :( long) tag; the first byte that becomes available on the socket will be appended to the given byte buffer. If necessary, the given buffer size will automatically increase. If the timeout value is negative, the read operation will not use timeout. If the buffer is empty, socket will create a buffer for us. If bufferOffset is greater than the length of the given buffer, this method will be useless and the delegate will not be called. If you pass a buffer, when AsyncSocket is used, you cannot change it in any way. The data returned by onSocket: didReadData: withTag will be a subset of the given buffer, that is, it will be referenced to the byte (void) readDataToLength :( NSUInterger) length withTimeout :( NSTimeInterval) timeout tag :( long) tag; read Take the given number of bytes. If the length is 0, the method will be useless and the delegate will not be called-(void) readDataToLength :( NSUInteger) length withTimeout :( NSTimeInterval) tiemout buffer :( NSMutableData *) buffer bufferOffset :( NSUInteger) offset tag :( long) tag; read the given number of bytes. At the beginning of the given offset, the bytes will be appended to the given byte buffer-(void) readDataToData :( NSData *) data withTimeout :( NSTimeInterval) timeout tag :( long) tag; read bytes until (including) if the input "data" parameter is separated by zero or zero length data is transmitted, the "data" parameter will be useless and the delegate will not be called to read a row from the socket, use "data" The parameter is used as the line separator (such as http crlf). Note that this method is not a character set. Therefore, if a separator appears, it can naturally be used as part of encoding, the read operation ends ahead of schedule-(void) readDataToData :( NSData *) data withTimeout :( NSTimeInterval) timeout buffer :( NSMutableData *) buffer bufferOffset :( NSUInteger) offset tag :( long) tag; read bytes until (including) the input as the separated "data" parameter, at the given offset, the bytes will be appended to the given byte buffer. Read a row from the socket and use the "data" parameter as the line separator (such as http crlf)-(void) writeData :( NSData *) data withTimeout :( NSTimeInterval) timeout tag :( long) tag; write data to the socket. when the request is complete, the delegate is called-(float) progressOfReadReturningTag :( long *) tag bytesDone :( NSUInteger *) done total :( NSUInteger *) total; -(float) progressOfWriteReturningTag :( long *) tag bytesDone :( NSUInteger *) done total :( NSUInteger *) total; returns the progress of the current read or write, from 0.0 to 1.0, or if there is no read/write, return Na N (check using isNan) tags, done, and total will be filled-(void) startTLS :( NSDictionary *) tlsSettings; make sure that the ssl/tls connection method can be called at any time. The tls handshake will occur after all pending read/write operations are completed. This is followed by a protocol option that sends a message dependent on StartTLS. It is upgraded to TLS at the same time in the queue without waiting for the write to complete. After this method is called, any read/write plan will occur in the secure link. for possible keys and TLS setting values, some of the possible keys are: *-kCFStreamSSLLevel *-variable *-kCFStreamSSLAllowsAnyRoot *-variable *-kCFStreamSSLPeerName *-kCFStreamSSLCertificates *-kCFStreamSSLIsServer if you pass an empty or empty dictionary, the default dictionary will be used. The default settings will be checked to ensure that the certificate is signed by a trusted third-party Certificate Authority and has no expired remote connection. However, it will not verify the name on the certificate, unless you give it a name, it is important to verify the security impact through the kCFStreamSSLPeerName key. Imagine you are trying to create a secure connection to MySecureServer.com, however, because of an attacked DNS server, your socket is directed to MaliciousServer.com. If you only use the default settings, MaliciousServer.com cannot monitor any problems with a valid default certificate setting, because the certificate is valid in this special case, to properly protect your connection, set kCFStreamSSLPeerName to MySecureServer.com. if you do not know the remote host with the same name beforehand (for example, you are not sure it is domain.com "or" www.domain.com "), you can use the default settings to verify the certificate, then, use the X509Certificate class for verification after the release is obtained. Part of the CocoaAsyncSocket open source project of the X509Certificate class-(void) enablePrebuffering for processing readDataToData requests, data must be read from the socket in small increments. The performance is greatly improved by allowing AsyncSocket to read large data blocks at a time and store any small internal buffer overflow. pre-buffering, it seems that some data may be read before you ask for it. If you use readDataToData frequently, using pre-buffering will provide better performance, in particular, the default pre-buffering status on the iphone is defined by DEFAULT_PREBUFFERING. We strongly recommend that you set it to yes. This method has some situations where pre-buffering requires some unforeseen reasons to be disabled by default, in this case, this method allows you to easily enable the pre-buffer-(BOOL) moveToRunLoop :( nsunloop *) runLoop when ready; when you create an AsyncSocket, it is added to the current thread runloop. You plan to use it on the thread for the socket manually created, it is the easiest way to create a socket on a thread. 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, it is best to combine this work in the same thread pool design if, however, in a separate thread, at a later time, you need to move a socket, this method can be used to complete tasks. This method must be called from the socket of the currently running thread/runloop. Note: After this method is called, all further methods should call this object from the given runloop. In addition, all delegate calls will be sent to the given runloop-(BOOL) setRunLoopModes :( NSArray *) runLoopModes;-(BOOL) addRunLoopMode :( NSString *) runLoopMode;-(BOOL) removeRunLoopMode :( NSString *) runLoopMode; allow you to configure the running cycle mode used by the socket. The default running cycle mode is "nsunloopcommonmodes". If you want your socket to continue in other modes, you may need to add the NSModalPanelRunLoopMode or NSEventTrackingRunLoopMode, or you may just want to use the socket that is accepted by the nsunloopcommonmodes to automatically inherit the same running cycle mode, just like listening to the socket. Note: the value of the nsunloopcommonmodes parameter is defined in 10.5, for previous versions, you can use kCFRunLoopCommonModes-(NSArray *) runLoopModes to return the currently running AsyncSocket instance. The default setting of run loop modes is nsdefaunultrloopmode-(NSData *) unreadData; an error event in onSocket: willDisconnectWithError: will be called to read any data that is left on the socket + (NSData *) CRLFData; // 0x0D0A + (NSData *) CRData; // 0x0D + (NSData *) LFData; // 0x0A + (NSData *) ZeroData; // 0x00 some common separators, in order to use readDataToData :.. method