iOS development get pictures and videos in the System album (with URL translation)

Source: Internet
Author: User

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

#import <AssetsLibrary/AssetsLibrary.h>//must import//photo original path # define Koriginalphotoimagepath [[ Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) objectatindex:0] stringbyappendingpathcomponent:@ "originalphotoimages"]//video URL Path # define Kvideourlpath [[ Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, 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) InitWithNibN AME: (NSString *) Nibnameornil Bundle: (NSBundle *) nibbundleornil{self = [Super Initwithnibname:nibnameornil Bundle:nibb    Undleornil]; if (self) {       Custom initialization} return self;}    -(void) viewdidload{[Super Viewdidload];    Do any 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];    Thumbnails of 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, BOOL *sto            P) {if (group! = nil) {[Weakself.grouparrays addobject:group];                    } else {[weakself.grouparrays enumerateobjectsusingblock:^ (id obj, Nsuinteger idx, BOOL *stop) { [obj enumerateassetsusingblock:^ (alasset *result, Nsuinteger index, BOOL *stop) {if ([result thumbnail]! = nil) {//Photo if ( [[Result Valueforproperty:alassetpropertytype] Isequaltostring:alassettypephoto]) {nsdate *date= [result Valueforproperty:alassetpropertydat                                E];                                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);                                    UI updates remember to put in the main thread, or else wait for the child thread to queue up don't know what age, will be very slow dispatch_async (Dispatch_get_main_queue (), ^{                                Self.litimgView.image = image;                            }); }//Video else if ([[Result Valueforproperty:alassetpropertytype] IsEq                            Ualtostring:alassettypevideo]) {//is similar to the picture method           }                        }         }];            }];                }        }; Alassetslibraryaccessfailureblock Failureblock = ^ (Nserror *error) {nsstring *errormessage                        = nil; switch ([error code]) {Case Alassetslibraryaccessuserdeniederror:case alassetslibraryacces                    Sgloballydeniederror:errormessage = @ "User denied access to the album, please open in < privacy >";                                    Break                    Default:errormessage = @ "Reason unknown.";            Break } dispatch_async (Dispatch_get_main_queue (), ^{uialertview *alertview = [[Uialertvie                                                                   W alloc]initwithtitle:@ "error, inaccessible!"                                                         Message:errormessage delegate:self         cancelbuttontitle:@ "OK"                                                Otherbuttontitles:nil, nil];            [Alertview show];        });                        };        Alassetslibrary *assetslibrary = [[Alassetslibrary alloc] init]; [Assetslibrary Enumerategroupswithtypes:alassetsgroupall Usingblock:listgroupblock FAI    Lureblock:failureblock]; });}

But

the path taken directly from the above method cannot be transferred and must be converted to a nsdata object to be re-written to the sandbox path

Convert the URL of the original image to NSData data, write to sandbox-(void) Imagewithurl: (nsurl *) URL withfilename: (NSString *) filename{//Enter this method should also be judged,    If you have already converted, do not call this method//How to determine has been converted, through the existence of the 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:koriginalphotoimagepat    H 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 the URL of the original video to NSData data, write to sandbox-(void) Videowithurl: (nsurl *) URL withfilename: (NSString *) filename{//Parse,    Why does the video not open itself up to the size of a memory write like a picture?    Think, if 1 video has more than 1G, is it 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) {[Assetlibrar Y assetforurl:url resultblock:^ (alasset *asset) {alassetrepresentation *rep = [Asset defaultrepresentation                ];                NSString * Videopath = [Kcachespath stringbyappendingpathcomponent:filename];                char const *CVIDEOPATH = [Videopath utf8string]; FILE *file = fopen (Cvideopath, "A + ");                    if (file) {const int buffersize = 1024 * 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:buffersize 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]; }    });}

@ Reprint please mark: Transfer from iOS world @ confused little book Thank you!

iOS development get pictures and videos in the System album (with URL translation)

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.