IOS Development acquisition System photo and video tutorials in photo album (with URL conversion) _ios

Source: Internet
Author: User

A few days did not write something, the company recently to do new projects, a little busy. Do not want my insistence on this interruption, I took my previous days to study the things to show you.

This is the use of assetslibrary and Photokit. I am a Virgo, a little obsessive, previously written in the project used is assetslibrary write the media file in the album, but Xcode always reported warning errors, although able to compile and display the effect, but more than 10 warning errors hanging in the mind is always not the taste, So I took a look at Assetlibrary and Photokit.

Prior to the advent of iOS 8, developers could only use the Assetslibrary framework to access the device's photo gallery, a framework that was a bit behind the pace of iOS application development and code design principles but really powerful, considering that IOS7 still had a lot of penetration, so assetslibrary Is the part of this article that focuses on this. After the advent of iOS8, Apple provided a framework called Photokit, a framework that allows applications to be better docked to the device photo gallery.

I. Composition of assetslibrary

The composition of the assetslibrary is in line with the composition of the photo library itself, the complete Photo gallery objects, albums, photos can be found in the Assetslibrary one by one corresponding composition, which makes the use of assetslibrary become intuitive and convenient. Want to know assetslibrary to start with its class.

Assetslibrary: Represents the resource pool (photo gallery) throughout the device and can be captured and included in the device by assetslibrary photos and videos

    • Alassetsgroup: Map an album in photo gallery, Alassetsgroup to get information about an album, resources under a photo album, and add resources to an album.
    • Alasset: Map a photo or video from a photo gallery, Alasset to get detailed information about a photo or video, or to save photos and videos.
    • Alassetrepresentation:alassetrepresentation is a alasset encapsulation (but not a subclass) that makes it easier to get resource information in Alasset, with at least one of each alasset Alassetrepresentation object, which can be obtained by defaultrepresentation. For example, using a system camera to take raw + JPEG photos, there will be two alassetrepresentation, one that encapsulates the raw information for the photo, and the other encapsulates the JPEG information for the photo.

@ words don't say more, directly on the code

#import <AssetsLibrary/AssetsLibrary.h>//Must be imported//photo artwork path #define KORIGINALPHOTOIMAGEPATH \ [[Nssearchpathfor Directoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) objectatindex:0] stringbyappendingpathcomponent:@ " Originalphotoimages "]//Video URL path #define KVIDEOURLPATH \ [[Nssearchpathfordirectoriesindomains (Nscachesdirectory, NS 
Userdomainmask, YES) objectatindex:0] stringbyappendingpathcomponent:@ "Videourl"]//caches path #define KCACHESPATH \ [Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) objectatindex:0]// 
Mainviewcontroller @interface Mthmainviewcontroller () @property (Nonatomic,strong) Mthnextviewcontroller *nextVC; 
@property (Nonatomic,strong) Nsmutablearray *grouparrays; 
 
@property (Nonatomic,strong) Uiimageview *litimgview; @end @implementation Mthmainviewcontroller-(ID) Initwithnibname: (NSString *) Nibnameornil Bundle: (NSBundle *) nibbund Leornil {self = [super Initwithnibname:nibnameorNil Bundle:nibbundleornil]; 
if (self) {//Custom initialization} return self; 
  }-(void) viewdidload {[Super viewdidload]; 
  Do no additional setup after loading the view. 
  Self.navigationItem.title = @ "Demo"; 
   
  Self.view.backgroundColor = [Uicolor Clearcolor]; 
   
  Initialize self.grouparrays = [Nsmutablearray array]; Test Baritem Self.navigationItem.rightBarButtonItem = [[Uibarbuttonitem alloc] initwithtitle:@ ' test ' style: 
   
  Uibarbuttonitemstyleplain target:self Action: @selector (TestRun)]; Test gesture Uipangesturerecognizer *panrecognizer = [[Uipangesturerecognizer alloc] initwithtarget:self action: @selector (d 
  Idclickpangesturerecognizer:)]; 
   
  [Self.navigationController.view Addgesturerecognizer:panrecognizer]; 
  Thumbnail images or videos show self.litimgview = [[Uiimageview alloc] Initwithframe:cgrectmake (100, 200, 120, 120)]; 
[Self.view Addsubview:_litimgview]; 
  }-(void) TestRun {__weak Mthmainviewcontroller *weakself = self; DiSpatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{ Alassetslibrarygroupsenumerationresultsblock Listgroupblock = ^ (Alassetsgroup *group, BOOLBOOL *stop) {if (group!) 
      = nil) {[Weakself.grouparrays addobject:group]; 
          else {[weakself.grouparrays enumerateobjectsusingblock:^ (id obj, Nsuinteger idx, Boolbool *stop) { [obj enumerateassetsusingblock:^ (alasset *result, Nsuinteger index, Boolbool *stop) {if ([result thumbnail]!= nil) {//Photo if ([[Result Valueforproperty:alassetp Ropertytype] Isequaltostring:alassettypephoto]) {nsdate *date= [result Valueforproperty 
                : Alassetpropertydate]; 
                UIImage *image = [uiimage imagewithcgimage:[result thumbnail]]; 
                NSString *filename = [[result defaultrepresentation] fileName]; 
                Nsurl *url = [[result defaultrepresentation] url]; int64_t FIlesize = [[result defaultrepresentation] size]; 
                NSLog (@ "date =%@", date); 
                NSLog (@ "filename =%@", filename); 
                NSLog (@ "url =%@", url); 
                 
                NSLog (@ "fileSize =%lld", fileSize); 
                  Updates to the UI remember to put it on the main thread, or wait for the child thread to come in line and not know what age, will be very slow dispatch_async (Dispatch_get_main_queue (), ^{ 
                Self.litimgView.image = image; 
              }); //Video else if ([[Result Valueforproperty:alassetpropertytype] Isequaltostring:alassettypev 
        IDEO]) {//And picture method similar}}}]; 
 
      }]; 
     
    } 
    }; 
       
      Alassetslibraryaccessfailureblock Failureblock = ^ (Nserror *error) {nsstring *errormessage = nil; switch ([error code]) {Case Alassetslibraryaccessuserdeniederror:case Alassetslibraryacce SsgloballydeNiederror:errormessage = @ "User denied access to albums, please open in < privacy >"; 
           
        Break 
          Default:errormessage = @ "Reason unknown."; 
      Break } dispatch_async (Dispatch_get_main_queue (), ^{uialertview *alertview = [[Uialertview Alloc]initwi 
                                  thtitle:@ "error, no access!"  
                             Message:errormessage delegate:self cancelbuttontitle:@ "OK" 
        Otherbuttontitles:nil, nil Nil]; 
      [Alertview show]; 
    }); 
     
     
    }; 
    Alassetslibrary *assetslibrary = [[Alassetslibrary alloc] init]; [Assetslibrary enumerategroupswithtypes:alassetsgroupall Usingblock:listgroupblock FailureBlock:failur 
  Eblock]; 
}); 
 }


@ but:
the path taken directly from the above method is not transmitted and must be converted to a NSData object to be rewritten to the sandbox path

   Converts the URL of the original picture to NSData data and writes to the sandbox-(void) Imagewithurl: (nsurl *) URL withfilename: (NSString *) fileName {//Enter this method should also 
  Plus, if you've already converted, don't call this method.//How to judge has been transformed, by whether there is a file path alassetslibrary *assetlibrary = [[Alassetslibrary alloc] init]; 
  Create a folder that holds the original diagram--->originalphotoimages nsfilemanager * filemanager = [Nsfilemanager Defaultmanager]; if (![ FileManager Fileexistsatpath:koriginalphotoimagepath]) {[FileManager Createdirectoryatpath: 
  Koriginalphotoimagepath withintermediatedirectories:yes Attributes:nil Error:nil]; 
      } dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{if (URL) {//Main method [Assetlibrary assetforurl:url resultblock:^ (Alasset *asset) 
        {Alassetrepresentation *rep = [Asset defaultrepresentation]; 
        Byte *buffer = (byte*) malloc ((unsigned long) rep.size); 
        Nsuinteger buffered = [Rep getbytes:buffer fromoffset:0.0 Length: ((unsigned long) rep.size) Error:nil]; NSData *data = [NSDATa datawithbytesnocopy:buffer length:buffered Freewhendone:yes]; 
        NSString * ImagePath = [Koriginalphotoimagepath stringbyappendingpathcomponent:filename]; 
      [Data Writetofile:imagepath Atomically:yes]; 
    } Failureblock:nil]; 
} 
  }); ///Convert original video URL to nsdata data, write sandbox-(void) Videowithurl: (nsurl *) URL withfilename: (NSString *) fileName {//Parse, why video 
  Not like a picture of a one-time open its own size of memory write? 
  Think, if 1 video has more than 1G, can directly open 1G more space to write? 
  Alassetslibrary *assetlibrary = [[Alassetslibrary alloc] init]; Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{if (URL) {[Assetlibrary Asse 
        Tforurl:url resultblock:^ (Alasset *asset) {alassetrepresentation *rep = [Asset defaultrepresentation]; 
        NSString * Videopath = [Kcachespath stringbyappendingpathcomponent:filename]; 
        char constconst *cvideopath = [Videopath utf8string]; 
        Filefile *file = fopen (Cvideopath, "A +"); if (file) {const int BuffersizE = 11024 * 1024; 
          Initializes a 1M buffer Byte *buffer = (byte*) malloc (buffersize); 
          Nsuinteger Read = 0, offset = 0, written = 0; 
          nserror* err = nil; if (rep.size!= 0) {do {read = [rep getbytes:buffer fromoffset:offset Length:buff 
              Ersize error:&err]; 
              Written = fwrite (buffer, sizeof (char), read, file); 
            Offset + = read; 
          while (read!= 0 &&!err);//no end, no error, OK continue}//release buffer, close file free (buffer); 
          buffer = NULL; 
          fclose (file); 
        File = NULL; 
    }} Failureblock:nil]; 
} 
  }); 
 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.