1. Download a picture from the Web to display it on the view
- (void) imagedownload{Dispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{ //the network path of the pictureNsurl *url = [Nsurl urlwithstring:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"]; //Loading PicturesNSData *data =[NSData Datawithcontentsofurl:url]; //Create a pictureUIImage *image =[UIImage Imagewithdata:data]; //back to main threadDispatch_async (Dispatch_get_main_queue (), ^{self.imageView.image=image; }); });}
2, download two pictures from the network, and so they both download finished, will they spell a picture.
@interface*ImageView; /* * * *image1; /* * * *image2; @end
- (void) group{dispatch_queue_t queue= Dispatch_get_global_queue (Dispatch_queue_priority_default,0); //Create a queue groupdispatch_group_t Group =dispatch_group_create (); //1. Download Picture 1Dispatch_group_async (group, queue, ^{ //the network path of the pictureNsurl *url = [Nsurl urlwithstring:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"]; //Loading PicturesNSData *data =[NSData Datawithcontentsofurl:url]; //Create a pictureSelf.image1 =[UIImage Imagewithdata:data]; }); //2. Download Picture 2Dispatch_group_async (group, queue, ^{ //the network path of the pictureNsurl *url = [Nsurl urlwithstring:@"http://pic38.nipic.com/20140228/5571398_215900721128_2.jpg"]; //Loading PicturesNSData *data =[NSData Datawithcontentsofurl:url]; //Create a pictureSelf.image2 =[UIImage Imagewithdata:data]; }); //3. Compose a new picture of picture 1, picture 2Dispatch_group_notify (group, queue, ^{ //to open a new graphics contextUigraphicsbeginimagecontext (Cgsizemake ( -, -)); //Drawing Pictures[Self.image1 Drawinrect:cgrectmake (0,0, -, -)]; [Self.image2 Drawinrect:cgrectmake ( -,0, -, -)]; //get the picture in contextUIImage *image =Uigraphicsgetimagefromcurrentimagecontext (); //End ContextUigraphicsendimagecontext (); //back to main thread display pictureDispatch_async (Dispatch_get_main_queue (), ^{ //4. Display the new pictureSelf.imageView.image =image; }); });}
Communication between IOS threads (GCD)