IOS Development block

Source: Internet
Author: User

Data storage

Plist,fmdb, archive. Transmission and analysis of network data, network transmission is recommended in JSON format data, less redundant data.

Data download down cache, can directly save the cache as a file, easy to handle the files in the cache. According to the needs of the set.

Block

1. What is block

Can greatly simplify the code, improve efficiency. Many important open source libraries are written in block, not necessarily written by themselves, but know how to write.

UI Development and network common function implementation callback, button event handling method is callback method, after the network download callback processing

(1). Button target action One method in the incoming button

(2). The table view passes in a pointer to self, and the callback attempts the method in the controller

(3). BLOCK: statement block. Resolve callbacks, which can be understood as "anonymous functions", defined in the method

Basic use of 2.block (syntax)

(1). Block variables

Skill, grammatical strange.

Block variables Store anonymous functions

The following is the definition of the block variable; the function name is block, variable type void (^block)

void (^block) ();

The following defines block statement blocks, which are then stored in the block variable

Block =^void () {

NSLog (@ "This is Block");

};

(2). Block statement blocks

(3) Parameters and return values

(4) Capturing external variables

(5) Block precautions

3.block application in development (OC,UI, network)

The application of 3.1 oc

Block's actual behavior and function are similar, the biggest difference is that the variable value can be accessed in the same scope. The block entity form is as follows: ^ (incoming parameter column) {behavior body};

The block entity starts with "^", followed by a parameter column wrapped in parentheses (such as int a, int b, int c), the body of the action is wrapped in braces, and the exclusive name is called block literal. The behavior subject can return the value by returning, and the type will be automatically identified by compiler. If there are no parameter columns to write: ^ (void).

The Block pointer is defined like this:

Callback Value (^ name) (parameter column);

For example, the following:

 void  (^block) ();    //  The following defines block statement blocks, which are then stored in the block variable  Block =^void   () {NSLog ( @ " this is block  "  ); };
int (^myadd) (int x,int y) = ^int (int x,int  y) {        return x+y;    };     int s =myadd (a);    NSLog (@ "s===%d", s);

Block use occasions

function pointers

Implementing a callback function

Qsort

Block's function type variable + statement block = = = Callback

Second, afnetworking Open Source Library

1, the introduction of afnetworking

Common ways to handle network requests

(1) nsurlconnection/nsurlsession

(2) Asjhttprequest not updated, less use

(3) Afnetworking: Recommended for use in projects

(4) Mknetworking

2. Get request

3 JSON download

4 DML Download

5.POST Request

6. File Upload

7. File download

8 Images Asynchronous loading

9 Judging network status

10 head

Asjhttprequest

//1 Get Request (Html,json,xml)//[self testgetrequest]; //2POST Request//[self testpostrequest]; //3 Uploading files, uploading images//[self testuploadfile]; //4. Download the file//[self testdownloadfile]; //5. Monitor network configuration[self testmonitornetworkstatus]; //6. Image asynchronous Download (can replace sdwebimage)//can add UIkit +afnetworking.h//7. Some requests have special request headers// }-(void) testmonitornetworkstatus{Afhttprequestoperationmanager*manager =[[afhttprequestoperationmanager alloc] Initwithbaseurl:[nsurl urlwithstring:@"www.baidu.com"]]; [Manager.reachabilitymanager Setreachabilitystatuschangeblock:^(afnetworkreachabilitystatus status) {nsdictionary*dict [email protected]{@ (afnetworkreachabilitystatusunknown):@"Unknown", @ (afnetworkreachabilitystatusnotreachable):@"not reached", @ (Afnetworkreachabilitystatusreachableviawwan):@"GPRS", @ (Afnetworkreachabilitystatusreachableviawifi):@"WIFI"}; NSLog (@"status is%@", dict[@ (status)]);    }]; //Turn on Status monitoring[Manager.reachabilitymanager startmonitoring];}-(void) testdownloadfile{//Create a Session Manager object (via default configuration)NSString *urlstring =@"Http://imgcache.qq.com/club/item/avatar/zip/7/i87/all.zip"; Afurlsessionmanager*manager =[[Afurlsessionmanager alloc] Initwithsessionconfiguration:[nsurlsessionconfiguration    Defaultsessionconfiguration]]; Nsurlsessiondownloadtask*task =[manager downloadtaskwithrequest:[nsurlrequest requestwithurl:[nsurl urlwithstring:urlstring]] Progress:nil Destination:^nsurl * (Nsurl *targetpath, Nsurlresponse *response) {NSString*path =[nsstring stringWithFormat:@"%@/documents/all.zip", Nshomedirectory ()]; NSLog (@"Path ==%@", path); return[Nsurl Fileurlwithpath:path]; } Completionhandler:^ (Nsurlresponse *response, Nsurl *filepath, Nserror *error) {NSLog (@"Download Wancheng");    }]; [Task resume]; //returns the location where the file was saved }//Test upload file-(void) testuploadfile{NSString*urlstring =@"http://quiet.local/uploadtest/upload.php"; //parameter name; Image: The value of the argument is a pictureAfhttprequestoperationmanager *manager =[Afhttprequestoperationmanager Manager]; Manager.responseserializer=[Afhttpresponseserializer Serializer]; [Manager post:urlstring Parameters:nil Constructingbodywithblock:^(ID<AFMultipartFormData>formData) {       //the uploaded data is attached to the request//mimetype There is one type for each fileNSString *path =[[nsbundle Mainbundle] Pathforresource:@"back2.jpg"Oftype:nil]; [FormData Appendpartwithfileurl:[nsurl Fileurlwithpath:path] Name:@"Image"FileName:@"jayzhang.jpg"MimeType:@"Image/jpeg"Error:nil]; } Success:^ (Afhttprequestoperation *operation,IDresponseobject) {NSString*str =[[NSString alloc] Initwithdata:responseobject encoding:nsutf8stringencoding]; NSLog (@"Str ===%@", str); } Failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@"Erro = =%@", error); }];}-(void) testpostrequest{//interface, post interface:http://quiet.local/testdir/login.phpNSString*urlstring1 =@"http://quiet.local/testdir/login.php"; Afhttprequestoperationmanager*manager =[Afhttprequestoperationmanager Manager]; Manager.responseserializer=[Afhttpresponseserializer Serializer]; [Manager post:urlstring1 parameters:@{@"User":@"Quiet",@"Password":@"123"} success:^ (Afhttprequestoperation *operation,IDresponseobject) {NSString*str =[[NSString alloc] Initwithdata:responseobject encoding:nsutf8stringencoding]; NSLog (@"Str ===%@", str); } Failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@"Erro = =%@", error);    }]; }-(void) testgetrequest{NSString*urlstring =@"http://www.baidu.com"; URLString=@"http://m.weather.com.cn/data/101010100.html"; //Define afnetworking ManagementAfhttprequestoperationmanager*manager =[Afhttprequestoperationmanager Manager]; //The default is that the data is Json,content-type and Json,responseobject is the parsed dictionary and array. Not generate error code =-1016, FIX: Set parser for HTTP form, download back is nsdata.Manager.responseserializer=[Afhttpresponseserializer Serializer]; [Manager get:urlstring Parameters:nil success:^ (Afhttprequestoperation *operation,IDresponseobject) {//NSLog (@ "A ==%@", responseobject);NSString*str =[[NSString alloc] Initwithdata:responseobject encoding:nsutf8stringencoding]; NSLog (@"Str ===%@", str); } Failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@"Erro = =%@", error); }];}

12 Network Basics

(1) Complete process of an HTTP request (important for iOS development)

Grab the bag.

(2) To open Baidu Web page for example, request (Get,post,delete,update). The request contains the HTTP type (get,post), Address (URL), protocol (HTTP, 1.1), request header, additional information;

The page is divided into two pages, a static HTML page, a dynamic php,asp,jsp page, and the data is returned to the browser and application via the response response.

(3) Get request, POST request

is a way to request, get is generally just to get the data, while Post gets the upload of additional data, all parameters of Get request are in the URL URLs, the POST request parameters are placed in the request header;

If you simply get the data, use the GET request, login to pass the password, upload the file or picture using the POST request.

IOS Development block

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.