纪念一下我的短暂的ios时光

日程文件格式ics.联系人通用格式vcf。其中 android一般使用2.1版本,ios使用3.0版本。 

iPhone 与 Android 实现音频互通,使用mp3.两个平台都有转换成mp3的成熟代码。

lame静态库是iOS将音频文件转为mp3的库。参考链接http://blog.csdn.net/ysy441088327/article/details/7392842

侧边栏使用的是UIViewController+RESideMenu.h,参考链接:http://blog.csdn.net/manoel/article/details/39013095/socket

socket使用的是GCDAsyncSocket,参考链接http://blog.csdn.net/xuqiang918/article/details/16864203

获取hostname使用getgateway和route类。

更改整个工程的工具栏背景

[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"Tittle.png"] forBarMetrics:UIBarMetricsDefault];

设置下一个界面的返回按钮样式

UIBarButtonItem *tmpItem=[[UIBarButtonItem alloc] init];

    

    tmpItem.title=@"返回";


self.navigationItem.backBarButtonItem= tmpItem;

    [self.navigationItem.backBarButtonItem setTintColor:[UIColor whiteColor]];


下面是具体获取能够转发给android的代码,学识有限有的代码应该不是最好的解决方案:

//获取通讯录中的所有属性,并存储在 textView 中,已检验,切实可行。兼容io6 ios 7 ,而且ios7还没有权限确认提示。

-(void)getContactData

{

    

    

    CFErrorRef error = NULL;

    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {

        

        if (granted) {

            //查询所有

            

            [self getAddressBook:@""];

        }

        

    });

    CFRelease(addressBook);

    

}


-(void)getAddressBook:(NSString*)searchText

{

     NSLog(@"get contact!!!");

    

    //如果没有授权则退出

    if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized) {

        return ;

    }

    

    CFErrorRef error = NULL;

    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

    

    

    if([searchText length]==0)

    {

        //查询所有

        self.listContacts = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));

        CFArrayRef arrayRef = ABAddressBookCopyArrayOfAllPeople(addressBook);//CFArrayCreate(kCFAllocatorDefault, (void *)self.listContacts, (CFIndex)(self.listContacts.count), NULL);

        

        _contactNums=CFArrayGetCount(arrayRef);

        //这里可以刷新collection

        self.lContactNums.text=[NSString stringWithFormat: @"%ld", _contactNums];

        NSLog(@"the contact nums is %ld",_contactNums);

        NSString* filePath = [self saveVCF:arrayRef];

        //[self generateVCardStringWithContacts:arrayRef];

        

    } else {

        //条件查询

        CFStringRef cfSearchText = (CFStringRef)CFBridgingRetain(searchText);

        

        self.listContacts = CFBridgingRelease(ABAddressBookCopyPeopleWithName(addressBook, cfSearchText));

        CFRelease(cfSearchText);

    }

    

    

    CFRelease(addressBook);

}



-(NSString*)saveVCF:(CFArrayRef)contacts {

    

    NSString *str = @"";

    //这里需要生成两种vcf文件一种2.1用于android,一种3.0用于ios用户

    str = [self generateVCardStringWithContacts_android:contacts];

//    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0) { // 5.0版本用系统自带的

//        CFDataRef vcards =nil;

//        vcards=(CFDataRef)ABPersonCreateVCardRepresentationWithPeople(contacts);

//        str = [[NSString alloc] initWithData:(NSData *)CFBridgingRelease(vcards) encoding:NSUTF8StringEncoding];

//       // CFrelease(vcards);

//        

//    }

//    else { //4.x 代码在这里哦~

//        str = [self generateVCardStringWithContacts:contacts];

//    }

    

    NSLog(@"save vcf str %@",str);

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    //通过KEY找到value

//    NSObject *object = [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas objectForKey:@"name"];

//    NSMutableDictionary *sendToNewphoneDatassss=[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas;

//    

//    if (object != nil) {

//        NSLog(@"通过KEY找到的value: %@",object);

//    }else{

//        NSLog(@"通过KEY没有找到value");

//        

//    }

    

    NSString *folderPath = [paths objectAtIndex:0];

    NSString *filePath = [folderPath stringByAppendingPathComponent:@"cloneit_contacts.vcf"];

    //str= [str stringByAppendingString:@"AAA"];

    [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

    

    NSLog(@"save vcf to path %@",filePath);

    

    NSLog(@"str: %@",str);

    

    NSFileManager* manager = [NSFileManager defaultManager];

    if ([manager fileExistsAtPath:filePath]){

         CPSelectedContent *selContent= [[CPSelectedContent alloc]init];

         selContent.contentName=@"cloneit_contacts.vcf";

         selContent.contentType=0;

         selContent.contentSize=[[manager attributesOfItemAtPath:filePath error:nil] fileSize];

        NSURL *url = [NSURL fileURLWithPath:filePath];

        selContent.contentUri=[url absoluteString];

        selContent.diffField=_contactNums;

        [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneContactDatas setObject:selContent forKey:selContent.contentUri];

        return filePath;

    }

    

    

    return NULL;

}




-(NSString*)generateVCardStringWithContacts:(CFArrayRef)contacts {

    NSInteger counter  = 0;

    NSString *vcard = @"";

    NSLog(@"generateVCardStringWithContacts");

    for(CFIndex i = 0; i < CFArrayGetCount(contacts); i++) {

        

        ABRecordRef person = CFArrayGetValueAtIndex(contacts, i);

        

        NSString *firstName = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));

        firstName = (firstName ? firstName : @"");

        NSString *lastName = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));

        lastName = (lastName ? lastName : @"");

        NSString *middleName = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonMiddleNameProperty));

        NSString *prefix = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonPrefixProperty));

        NSString *suffix = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonSuffixProperty));

        NSString *nickName = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonNicknameProperty));

        NSString *firstNamePhonetic = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty));

        NSString *lastNamePhonetic = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty));

        

        NSString *organization = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonOrganizationProperty));

        NSString *jobTitle = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonJobTitleProperty));

        NSString *department = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonDepartmentProperty));

        

        NSString *compositeName = [NSString stringWithFormat:@"%@%@",firstName,lastName];

        

        if(i > 0) {

            vcard = [vcard stringByAppendingFormat:@"\n"];

        }

//正常的

//        vcard = [vcard stringByAppendingFormat:@"BEGIN:VCARD\nVERSION:3.0\nN:%@;%@;%@;%@;%@\n",

//                 (firstName ? firstName : @""),

//                 (lastName ? lastName : @""),

//                 (middleName ? middleName : @""),

//                 (prefix ? prefix : @""),

//                 (suffix ? suffix : @"")

//                 ];

        //适配android手机的

        vcard = [vcard stringByAppendingFormat:@"BEGIN:VCARD\nVERSION:3.0\nN:%@;%@;%@;%@;%@\n",

                 (firstName ? firstName : @""),

                 (lastName ? lastName : @""),

                 (middleName ? middleName : @""),

                 (prefix ? prefix : @""),

                 (suffix ? suffix : @"")

                 ];

        

        vcard = [vcard stringByAppendingFormat:@"FN:%@\n",compositeName];

        if(nickName) vcard = [vcard stringByAppendingFormat:@"NICKNAME:%@\n",nickName];

        if(firstNamePhonetic) vcard = [vcard stringByAppendingFormat:@"X-PHONETIC-FIRST-NAME:%@\n",firstNamePhonetic];

        if(lastNamePhonetic) vcard = [vcard stringByAppendingFormat:@"X-PHONETIC-LAST-NAME:%@\n",lastNamePhonetic];

        

        // Work

        if(organization) vcard = [vcard stringByAppendingFormat:@"ORG:%@;%@\n",(organization?organization:@""),(department?department:@"")];

        

        if(jobTitle) vcard = [vcard stringByAppendingFormat:@"TITLE:%@\n",jobTitle];

        

        // Mail

        ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);

        if(emails) {

            for (int k = 0; k < ABMultiValueGetCount(emails); k++) {

                NSString *label = (NSString*)CFBridgingRelease(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(emails, k)));

                NSString *email = (NSString *)CFBridgingRelease(ABMultiValueCopyValueAtIndex(emails, k));

                NSString *labelLower = [label lowercaseString];

                

                vcard = [vcard stringByAppendingFormat:@"EMAIL;type=INTERNET;type=WORK:%@\n",email];

                

                if ([labelLower isEqualToString:@"home"]) vcard = [vcard stringByAppendingFormat:@"EMAIL;type=INTERNET;type=HOME:%@\n",email];

                else if ([labelLower isEqualToString:@"work"]) vcard = [vcard stringByAppendingFormat:@"EMAIL;type=INTERNET;type=WORK:%@\n",email];

                else {//类型解析不出来的

                    counter++;

                    vcard = [vcard stringByAppendingFormat:@"item%ld.EMAIL;type=INTERNET:%@\nitem%ld.X-ABLabel:%@\n",(long)counter,email,(long)counter,label];

                }

            }

        }

        

        // Tel

        ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);

        if(phoneNumbers) {

            for (int k = 0; k < ABMultiValueGetCount(phoneNumbers); k++) {

                NSString *label = (NSString*)CFBridgingRelease(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phoneNumbers, k)));

                NSString *number = (NSString *)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phoneNumbers, k));

                NSString *labelLower = [label lowercaseString];

                

                if ([labelLower isEqualToString:@"mobile"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=CELL:%@\n",number];

                else if ([labelLower isEqualToString:@"home"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=HOME:%@\n",number];

                else if ([labelLower isEqualToString:@"work"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=WORK:%@\n",number];

                else if ([labelLower isEqualToString:@"main"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=MAIN:%@\n",number];

                else if ([labelLower isEqualToString:@"homefax"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=HOME;type=FAX:%@\n",number];

                else if ([labelLower isEqualToString:@"workfax"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=WORK;type=FAX:%@\n",number];

                else if ([labelLower isEqualToString:@"pager"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=PAGER:%@\n",number];

                else if([labelLower isEqualToString:@"other"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=OTHER:%@\n",number];

                else { //类型解析不出来的

                    counter++;

                    vcard = [vcard stringByAppendingFormat:@"item%ld.TEL:%@\nitem%ld.X-ABLabel:%@\n",(long)counter,number,(long)counter,label];

                }

            }

        }

        

        // Address

        ABMultiValueRef address = ABRecordCopyValue(person, kABPersonAddressProperty);

        if(address) {

            for (int k = 0; k < ABMultiValueGetCount(address); k++) {

                NSString *label =nil;

                label= (NSString*)CFBridgingRelease(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(CFBridgingRetain(label), k)));

                NSDictionary *dic = (NSDictionary *)CFBridgingRelease(ABMultiValueCopyLabelAtIndex(address, k));

                NSString *labelLower = [label lowercaseString];

                NSString* country = [dic valueForKey:(NSString *)kABPersonAddressCountryKey];

                NSString* city = [dic valueForKey:(NSString *)kABPersonAddressCityKey];

                NSString* state = [dic valueForKey:(NSString *)kABPersonAddressStateKey];

                NSString* street = [dic valueForKey:(NSString *)kABPersonAddressStreetKey];

                NSString* zip = [dic valueForKey:(NSString *)kABPersonAddressZIPKey];

                NSString* countryCode = [dic valueForKey:(NSString *)kABPersonAddressCountryCodeKey];

                NSString *type = @"";

                NSString *labelField = @"";

                counter++;

                

                if([labelLower isEqualToString:@"work"]) type = @"WORK";

                else if([labelLower isEqualToString:@"home"]) type = @"HOME";

                else if(label && [label length] > 0)

                {

                    labelField = [NSString stringWithFormat:@"item%ld.X-ABLabel:%@\n",(long)counter,label];

                }

                

                vcard = [vcard stringByAppendingFormat:@"item%ld.ADR;type=%@:;;%@;%@;%@;%@;%@\n%@item%ld.X-ABADR:%@\n",

                         (long)counter,

                         type,

                         (street ? street : @""),

                         (city ? city : @""),

                         (state ? state : @""),

                         (zip ? zip : @""),

                         (country ? country : @""),

                         labelField,

                         (long)counter,

                         (countryCode ? countryCode : @"")

                         ];

            }

        }

        

        

        // 剩下的不常用暂时不写以后增加

        // url

        // TODO:

        

        // IM

        // TODO:

        

        // Photo

        // TODO:

        

        vcard = [vcard stringByAppendingString:@"END:VCARD"];

    }

    

    return vcard;

}


-(NSString*)generateVCardStringWithContacts_android:(CFArrayRef)contacts {

    NSInteger counter  = 0;

    NSString *vcard = @"";

    NSLog(@"generateVCardStringWithContacts");

    //

    for(CFIndex i = 0; i < CFArrayGetCount(contacts); i++) {

        

        ABRecordRef person = CFArrayGetValueAtIndex(contacts, i);

        

        NSString *firstName = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));

        firstName = (firstName ? firstName : @"");

        NSString *lastName = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));

        lastName = (lastName ? lastName : @"");

        NSString *middleName = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonMiddleNameProperty));

        NSString *prefix = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonPrefixProperty));

        NSString *suffix = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonSuffixProperty));

        NSString *nickName = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonNicknameProperty));

        NSString *firstNamePhonetic = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty));

        NSString *lastNamePhonetic = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty));

        

        NSString *organization = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonOrganizationProperty));

        NSString *jobTitle = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonJobTitleProperty));

        NSString *department = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonDepartmentProperty));

        

        NSString *compositeName = [NSString stringWithFormat:@"%@%@",firstName,lastName];

        

        if(i > 0) {

            vcard = [vcard stringByAppendingFormat:@"\n"];

        }

        //适配android手机的

        vcard = [vcard stringByAppendingFormat:@"BEGIN:VCARD\nVERSION:2.1\nN:%@;%@;%@;%@;%@\n",

                 (firstName ? firstName : @""),

                 (lastName ? lastName : @""),

                 (middleName ? middleName : @""),

                 (prefix ? prefix : @""),

                 (suffix ? suffix : @"")

                 ];

        

        vcard = [vcard stringByAppendingFormat:@"FN:%@\n",compositeName];

//        if(nickName) vcard = [vcard stringByAppendingFormat:@"NICKNAME:%@\n",nickName];

//        if(firstNamePhonetic) vcard = [vcard stringByAppendingFormat:@"X-PHONETIC-FIRST-NAME:%@\n",firstNamePhonetic];

//        if(lastNamePhonetic) vcard = [vcard stringByAppendingFormat:@"X-PHONETIC-LAST-NAME:%@\n",lastNamePhonetic];

        

        // Work

//        if(organization) vcard = [vcard stringByAppendingFormat:@"ORG:%@;%@\n",(organization?organization:@""),(department?department:@"")];

//        

//        if(jobTitle) vcard = [vcard stringByAppendingFormat:@"TITLE:%@\n",jobTitle];

//        

        // Mail

//        ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);

//        if(emails) {

//            for (int k = 0; k < ABMultiValueGetCount(emails); k++) {

//                NSString *label = (NSString*)CFBridgingRelease(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(emails, k)));

//                NSString *email = (NSString *)CFBridgingRelease(ABMultiValueCopyValueAtIndex(emails, k));

//                NSString *labelLower = [label lowercaseString];

//                

//                vcard = [vcard stringByAppendingFormat:@"EMAIL;type=INTERNET;type=WORK:%@\n",email];

//                

//                if ([labelLower isEqualToString:@"home"]) vcard = [vcard stringByAppendingFormat:@"EMAIL;type=INTERNET;type=HOME:%@\n",email];

//                else if ([labelLower isEqualToString:@"work"]) vcard = [vcard stringByAppendingFormat:@"EMAIL;type=INTERNET;type=WORK:%@\n",email];

//                else {//类型解析不出来的

//                    counter++;

//                    vcard = [vcard stringByAppendingFormat:@"item%ld.EMAIL;type=INTERNET:%@\nitem%ld.X-ABLabel:%@\n",(long)counter,email,(long)counter,label];

//                }

//            }

//        }

        

        // Tel

        ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);

        if(phoneNumbers) {

            for (int k = 0; k < ABMultiValueGetCount(phoneNumbers); k++) {

                NSString *label = (NSString*)CFBridgingRelease(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phoneNumbers, k)));

                NSString *number = (NSString *)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phoneNumbers, k));

                 number = [number stringByReplacingOccurrencesOfString:@"-" withString:@""];

                NSString *labelLower = [label lowercaseString];

                

                if ([labelLower isEqualToString:@"mobile"]) vcard = [vcard stringByAppendingFormat:@"TEL;CELL;PREF:%@\n",number];

                else if ([labelLower isEqualToString:@"home"]) vcard = [vcard stringByAppendingFormat:@"TEL;HOME;PREF:%@\n",number];

                else if ([labelLower isEqualToString:@"work"]) vcard = [vcard stringByAppendingFormat:@"TEL;WORK;PREF:%@\n",number];

                else if ([labelLower isEqualToString:@"main"]) vcard = [vcard stringByAppendingFormat:@"TEL;MAIN;PREF:%@\n",number];

                else if ([labelLower isEqualToString:@"homefax"]) vcard = [vcard stringByAppendingFormat:@"TEL;HOME;FAX;PREF:%@\n",number];

                else if ([labelLower isEqualToString:@"workfax"]) vcard = [vcard stringByAppendingFormat:@"TEL;WORK;FAX;PREF:%@\n",number];

                else if ([labelLower isEqualToString:@"pager"]) vcard = [vcard stringByAppendingFormat:@"TEL;PAGER;PREF:%@\n",number];

                else if([labelLower isEqualToString:@"other"]) vcard = [vcard stringByAppendingFormat:@"TEL;OTHER;PREF:%@\n",number];

                else { //类型解析不出来的

                    counter++;

                    vcard = [vcard stringByAppendingFormat:@"item%ld.TEL:%@\nitem%ld.X-ABLabel:%@\n",(long)counter,number,(long)counter,label];

                }

            }

        }

        

        // Address

//        ABMultiValueRef address = ABRecordCopyValue(person, kABPersonAddressProperty);

//        if(address) {

//            for (int k = 0; k < ABMultiValueGetCount(address); k++) {

//                NSString *label =nil;

//                label= (NSString*)CFBridgingRelease(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(CFBridgingRetain(label), k)));

//                NSDictionary *dic = (NSDictionary *)CFBridgingRelease(ABMultiValueCopyLabelAtIndex(address, k));

//                NSString *labelLower = [label lowercaseString];

//                NSString* country = [dic valueForKey:(NSString *)kABPersonAddressCountryKey];

//                NSString* city = [dic valueForKey:(NSString *)kABPersonAddressCityKey];

//                NSString* state = [dic valueForKey:(NSString *)kABPersonAddressStateKey];

//                NSString* street = [dic valueForKey:(NSString *)kABPersonAddressStreetKey];

//                NSString* zip = [dic valueForKey:(NSString *)kABPersonAddressZIPKey];

//                NSString* countryCode = [dic valueForKey:(NSString *)kABPersonAddressCountryCodeKey];

//                NSString *type = @"";

//                NSString *labelField = @"";

//                counter++;

//                

//                if([labelLower isEqualToString:@"work"]) type = @"WORK";

//                else if([labelLower isEqualToString:@"home"]) type = @"HOME";

//                else if(label && [label length] > 0)

//                {

//                    labelField = [NSString stringWithFormat:@"item%ld.X-ABLabel:%@\n",(long)counter,label];

//                }

//                

//                vcard = [vcard stringByAppendingFormat:@"item%ld.ADR;type=%@:;;%@;%@;%@;%@;%@\n%@item%ld.X-ABADR:%@\n",

//                         (long)counter,

//                         type,

//                         (street ? street : @""),

//                         (city ? city : @""),

//                         (state ? state : @""),

//                         (zip ? zip : @""),

//                         (country ? country : @""),

//                         labelField,

//                         (long)counter,

//                         (countryCode ? countryCode : @"")

//                         ];

//            }

//        }

        

        

        // 剩下的不常用暂时不写以后增加

        // url

        // TODO:

        

        // IM

        // TODO:

        

        // Photo

        // TODO:

        

        vcard = [vcard stringByAppendingString:@"END:VCARD"];

    }

    

    return vcard;

}


//查询所有的音乐文件

-(void)QueryAllMusic

{

    MPMediaQuery *everything = [[MPMediaQuery alloc] init];

    NSLog(@"Logging items from a generic query...");

    NSArray *itemsFromGenericQuery = [everything items];

    NSLog(@"count = %lu", (unsigned long)itemsFromGenericQuery.count);

    

    _audioNums=itemsFromGenericQuery.count;

    

    if (_audioNums==0) {

        return;

    }

    _LAudioNums.text=[NSString stringWithFormat: @"%ld", _audioNums];

    NSFileManager* manager = [NSFileManager defaultManager];

    for (MPMediaItem *song in itemsFromGenericQuery)

    {

        NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle];

        NSString *songArtist = [song valueForProperty:MPMediaItemPropertyArtist];

        NSURL* assetUrl = [song valueForProperty:MPMediaItemPropertyAssetURL];

        NSLog (@"Title:%@, Aritist:%@", songTitle, songArtist);

        

        //NSString *filePathfromUrl = [assetUrl path];

        //NSString *fileAudioName = [filePathfromUrl lastPathComponent];

        // 获得文件名(不带后缀)

        // exestr = [exestr stringByDeletingPathExtension];

        // 获得文件的后缀名(不带'.'

        //exestr = [filePath pathExtension];

        

        

        

        

        

        AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetUrl options:nil];

        AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset presetName: AVAssetExportPresetAppleM4A];

        

        exporter.outputFileType = @"com.apple.m4a-audio";

        

        NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,      NSUserDomainMask, YES);

        

        NSString *documentDirectory = [directoryPaths objectAtIndex:0];

        

        NSString *exportFile = [documentDirectory stringByAppendingPathComponent: songTitle];

        exportFile = [exportFile stringByAppendingString: @".m4a"];

        //如果这个文件存在就删除这个文件。

        if ([manager fileExistsAtPath:exportFile])

        {

            NSError *deleteErr = nil;

            [manager removeItemAtPath:exportFile error:&deleteErr];

            if (deleteErr)

            {

                NSLog (@"Can't delete %@: %@", exportFile, deleteErr);

            }

        }

        //复制数据到临时文件夹内

        NSURL *path_url = [NSURL fileURLWithPath:exportFile];

        exporter.outputURL = path_url;

        [exporter exportAsynchronouslyWithCompletionHandler:^{

            int exportStatus = exporter.status;

            switch (exportStatus)

            {

                case AVAssetExportSessionStatusFailed:

                {

                    // log error to text view

                    NSError *exportError = exporter.error;

                    NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);

                    break;

                }

                case AVAssetExportSessionStatusCompleted:

                {

                    NSLog (@"AVAssetExportSessionStatusCompleted");

                    // set up AVPlayer

                    //NSData *data = [NSData dataWithContentsOfURL:path_url];

                    //复制完成,加入购物车,准备发送给android端。

                    //NSString *filePathfromUrl = [path_url path];

                    //NSString *fileAudioName = [filePathfromUrl lastPathComponent];

                    

                    CPSelectedContent *selContent= [[CPSelectedContent alloc]init];

                    selContent.contentName=[[[songTitle stringByAppendingString:@"_"]stringByAppendingString:songArtist]stringByAppendingString:@".mp3"];

                    selContent.contentType=5;//5代表音乐

                    selContent.contentSize=[[manager attributesOfItemAtPath:exportFile error:nil] fileSize];

                    

                    selContent.contentUri=[path_url absoluteString];

                    selContent.diffField=_audioNums;

                    [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas setObject:selContent forKey:selContent.contentUri];

                    

                    

                    

                    break;

                }

                case AVAssetExportSessionStatusUnknown:

                {

                    NSLog (@"AVAssetExportSessionStatusUnknown");

                    break;

                }

                case AVAssetExportSessionStatusExporting:

                {

                    NSLog (@"AVAssetExportSessionStatusExporting");

                    break;

                }

                case AVAssetExportSessionStatusCancelled:

                {

                    NSLog (@"AVAssetExportSessionStatusCancelled");

                    break;

                }

                case AVAssetExportSessionStatusWaiting:

                {

                    NSLog (@"AVAssetExportSessionStatusWaiting");

                    break;

                }

                default:

                {

                    NSLog (@"didn't get export status");

                    break;

                }

            }

        }];

        

        

        

        /

        

        

        

        

    }

    

    

    

    

    

    

    

   

    

    

    /

    

}





//查询所有的音乐文件

-(void)QueryAllMusic_Android

{

   

        MPMediaQuery *everything = [[MPMediaQuery alloc] init];

        NSLog(@"Logging items from a generic query...");

        NSArray *itemsFromGenericQuery = [everything items];

        NSLog(@"count = %lu", (unsigned long)itemsFromGenericQuery.count);

        

        _audioNums=itemsFromGenericQuery.count;

        

        if (_audioNums==0) {

            return;

        }

        _LAudioNums.text=[NSString stringWithFormat: @"%ld", _audioNums];

        NSFileManager* manager = [NSFileManager defaultManager];

        for (MPMediaItem *song in itemsFromGenericQuery)

        {

            NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle];

            NSString *songArtist = [song valueForProperty:MPMediaItemPropertyArtist];

            NSURL* assetUrl = [song valueForProperty:MPMediaItemPropertyAssetURL];

            NSLog (@"Title:%@, Aritist:%@", songTitle, songArtist);

            

            NSString *fileName= [[songTitle stringByAppendingString:@"_"] stringByAppendingString:songArtist];

            

            

            //如果存在这首歌的mp3则不再重新生成,如果不存在旧生成新的mp3.

            

            

            NSString* KOriginalAudioPath=[[[NSHomeDirectory() stringByAppendingFormat:@"/Documents/" ]stringByAppendingPathComponent:fileName]stringByAppendingString:@".mp3"];

            

            if (![[NSFileManager defaultManager] fileExistsAtPath:KOriginalAudioPath]) {

                [self convertToCAF:fileName SONG:song];

            }else {

                CPSelectedContent *selContent= [[CPSelectedContent alloc]init];

                selContent.contentName=KOriginalAudioPath;

                selContent.contentType=5;//5代表音乐

                selContent.contentSize=[[[NSFileManager defaultManager] attributesOfItemAtPath:KOriginalAudioPath error:nil] fileSize];

                NSLog(@"%ld",selContent.contentSize);

                

                selContent.contentUri=[[NSURL fileURLWithPath:KOriginalAudioPath ] absoluteString];

                selContent.diffField=_audioNums;

                [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneAudioDatas setObject:selContent forKey:selContent.contentUri];

            }

            

            

            

            


        }

        

        

        

        

        

        

       

        

        

        /

        

}




-(void)QueryAllVideoAndPic

{

    _videoNums=0;

    _picNums=0;

    

    __weak CPGetDataViewController *weakSelf = self;

    weakSelf.groupArrays= [NSMutableArray arrayWithCapacity:5];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop) {

            if (group != nil) {

                [weakSelf.groupArrays addObject:group];

                NSLog(@"groupis nil!");

            } else {

                

                [weakSelf.groupArrays enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

                    [obj enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {

                        if ([result thumbnail] != nil) {

                            

                            // 照片

                            if ([[result valueForProperty:ALAssetPropertyType] 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];

                                

                                 NSString* KOriginalPhotoImagePath=[[NSHomeDirectory() stringByAppendingFormat:@"/Documents/" ]stringByAppendingPathComponent:fileName];

                                //[self imageWithUrl:url withFileName:fileName];

                                if (![[NSFileManager defaultManager] fileExistsAtPath:KOriginalPhotoImagePath]) {

                                    [self imageWithUrl:url withFileName:fileName];

                                }else{

                                    //加入CPSelectedContent

                                    //if([fileName isEqualToString:@"IMG_1415.PNG"]){

                                        CPSelectedContent *selContent= [[CPSelectedContent alloc]init];

                                        selContent.contentName=fileName;

                                        selContent.contentType=3;//5代表音乐

                                        selContent.contentSize=[[[NSFileManager defaultManager] attributesOfItemAtPath:KOriginalPhotoImagePath error:nil] fileSize];

                                        NSLog(@"%ld",selContent.contentSize);

                                        

                                        selContent.contentUri=[[NSURL fileURLWithPath:KOriginalPhotoImagePath ] absoluteString];

                                        selContent.diffField=_picNums;

                                        [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphonePicDatas setObject:selContent forKey:selContent.contentUri];

                                 //   }

                                    

                                }

                                

                                

                                

                                //NSLog(@"date = %@",date);

                                //NSLog(@"picfileName = %@",fileName);

                                //NSLog(@"url = %@",url);

                                //NSLog(@"fileSize = %lld",fileSize);

                                _picNums++;

                                //NSLog(@"_picNums = %d",_picNums);

                                NSLog(@"index = %d",index);

                                

                                // UI的更新记得放在主线程,要不然等子线程排队过来都不知道什么年代了,会很慢的

                                dispatch_async(dispatch_get_main_queue(), ^{

                                    

                                    self.litimgView.image = image;

                                });

                            }

                            // 视频

                            else if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo] ){

                                

                                // 和图片方法类似

                                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];

                                

                                

                                NSString* KOriginalVideoPath=[[NSHomeDirectory() stringByAppendingFormat:@"/Documents/" ]stringByAppendingPathComponent:fileName];

                                

                                if (![[NSFileManager defaultManager] fileExistsAtPath:KOriginalVideoPath]) {

                                    [self videoWithUrl:url withFileName:fileName];

                                }else{

                                    //加入到selectedcontent

                                    CPSelectedContent *selContent= [[CPSelectedContent alloc]init];

                                    selContent.contentName=fileName ;

                                    selContent.contentType=4;//5代表音乐

                                    selContent.contentSize=[[[NSFileManager defaultManager] attributesOfItemAtPath:KOriginalVideoPath error:nil] fileSize];

                                    NSLog(@"%ld",selContent.contentSize);

                                    

                                    selContent.contentUri=[[NSURL fileURLWithPath:KOriginalVideoPath ] absoluteString];

                                    selContent.diffField=_videoNums;

                                    [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneVideoDatas setObject:selContent forKey:selContent.contentUri];

                                }

                                

                                

                                

                                //NSLog(@"date = %@",date);

                                //NSLog(@"videofileName = %@",fileName);

                                //NSLog(@"url = %@",url);

                                //NSLog(@"fileSize = %lld",fileSize);

                                

                                _videoNums=_videoNums+1;

                                NSLog(@"_videoNums = %d",_videoNums);

                                //NSLog(@"indexvideo = %@",index);

                            }

                        }

                    }];

                }];

                dispatch_async(dispatch_get_main_queue(), ^{

                    

                

                    _lPicNums.text=[NSString stringWithFormat: @"%d",[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphonePicDatas.count ];

                    _lVideoNums.text=[NSString stringWithFormat: @"%d",[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneVideoDatas.count];


                });

              }

            NSLog(@"islaset !");

            };

        

        ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error)

        {

            

            NSString *errorMessage = nil;

            

            switch ([error code]) {

                case ALAssetsLibraryAccessUserDeniedError:

                case ALAssetsLibraryAccessGloballyDeniedError:

                    errorMessage = @"用户拒绝访问相册,请在<隐私>中开启";

                    break;

                    

                default:

                    errorMessage = @"Reason unknown.";

                    break;

            }

            

            dispatch_async(dispatch_get_main_queue(), ^{

                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"错误,无法访问!"

                                                                   message:errorMessage

                                                                  delegate:self

                                                         cancelButtonTitle:@"确定"

                                                         otherButtonTitles:nil, nil, nil];

                [alertView show];

            });

        };

        

        

        ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary allocinit];

        [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll

                                     usingBlock:listGroupBlock failureBlock:failureBlock];

    });

    

}


- (void) convertCAfToMp3:(NSString *)filename

{

    

    NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectoryPath = [dirs objectAtIndex:0];

   NSString *exportPath = [documentsDirectoryPath stringByAppendingPathComponent:filename] ;

    

        NSString *cafFileName = filename;

    NSString *cafFilePath = [documentsDirectoryPath stringByAppendingPathComponent:cafFileName];//[[NSHomeDirectory() stringByAppendingFormat:@"/Documents/"] stringByAppendingPathComponent:cafFileName];

        NSString *mp3FileName = [cafFileName stringByAppendingString:@".mp3"];

        NSString *mp3FilePath = [documentsDirectoryPath stringByAppendingPathComponent:mp3FileName] ;//[[NSHomeDirectory() stringByAppendingFormat:@"/Documents/"] stringByAppendingPathComponent:mp3FileName];

    if ([[NSFileManager defaultManager] fileExistsAtPath:mp3FilePath]) {

        [[NSFileManager defaultManager] removeItemAtPath:mp3FilePath error:nil];

    }

    if (![[NSFileManager defaultManager] fileExistsAtPath:cafFilePath]) {

       NSLog(@"path %@ is not exist",cafFilePath);

    }


        

        @try {

            int read, write;

            

            FILE *pcm = fopen([cafFilePath cStringUsingEncoding:NSUTF8StringEncoding], "rb");  //source

            fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header

            FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:NSUTF8StringEncoding], "wb");  //output

            

            const int PCM_SIZE = 8192;

            const int MP3_SIZE = 8192;

            short int pcm_buffer[PCM_SIZE*2];

            unsigned char mp3_buffer[MP3_SIZE];

            

            lame_t lame = lame_init();

            lame_set_in_samplerate(lame, 44100);

            lame_set_VBR(lame, vbr_default);

            lame_init_params(lame);

            

            do {

                read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);

                if (read == 0)

                    write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);

                else

                    write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);

                

                fwrite(mp3_buffer, write, 1, mp3);

                

            } while (read != 0);

            

            lame_close(lame);

            fclose(mp3);

            fclose(pcm);

        }

        @catch (NSException *exception) {

            NSLog(@"%@",[exception description]);

        }

        @finally {

            [self performSelectorOnMainThread:@selector(convertMp3Finish)

                                   withObject:nil

                                waitUntilDone:YES];

            //加入到selectedcontent

            CPSelectedContent *selContent= [[CPSelectedContent alloc]init];

            selContent.contentName=[filename stringByAppendingString:@".mp3"];

            selContent.contentType=5;//5代表音乐

            selContent.contentSize=[[[NSFileManager defaultManager] attributesOfItemAtPath:mp3FilePath error:nil] fileSize];

            NSLog(@"%ld",selContent.contentSize);

            

            selContent.contentUri=[[NSURL fileURLWithPath:mp3FilePath ] absoluteString];

            selContent.diffField=_audioNums;

            [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneAudioDatas setObject:selContent forKey:selContent.contentUri];

        }

    

}


- (void) convertToCAF:(NSString *)filename  SONG:(MPMediaItem *)song

{

    NSURL *assetURL = [song valueForProperty:MPMediaItemPropertyAssetURL];

    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];

    

    NSError *assetError = nil;

    AVAssetReader *assetReader = [AVAssetReader assetReaderWithAsset:songAsset error:&assetError];

    if (assetError) {

        NSLog (@"error: %@", assetError);

        return;

    }

    

    AVAssetReaderOutput *assetReaderOutput = [AVAssetReaderAudioMixOutput

                                               assetReaderAudioMixOutputWithAudioTracks:songAsset.tracks

                                               audioSettings: nil]

                                              ;

    if (! [assetReader canAddOutput: assetReaderOutput]) {

        NSLog (@"can't add reader output... die!");

        return;

    }

    [assetReader addOutput: assetReaderOutput];

    

    NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectoryPath = [dirs objectAtIndex:0];

    NSString *exportPath = [documentsDirectoryPath stringByAppendingPathComponent:filename] ;

    if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {

        [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];

    }

    NSURL *exportURL = [NSURL fileURLWithPath:exportPath];

    AVAssetWriter *assetWriter = [AVAssetWriter assetWriterWithURL:exportURL

                                                           fileType:AVFileTypeCoreAudioFormat

                                                              error:&assetError]

                                 ;

    if (assetError) {

        NSLog (@"error: %@", assetError);

        return;

    }

    AudioChannelLayout channelLayout;

    memset(&channelLayout, 0, sizeof(AudioChannelLayout));

    channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;

    NSDictionary *outputSettings = [NSDictionary dictionaryWithObjectsAndKeys:

                                    [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,

                                    [NSNumber numberWithFloat:44100.0], AVSampleRateKey,

                                    [NSNumber numberWithInt:2], AVNumberOfChannelsKey,

                                    [NSData dataWithBytes:&channelLayout length:sizeof(AudioChannelLayout)], AVChannelLayoutKey,

                                    [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,

                                    [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,

                                    [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,

                                    [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,

                                    nil];

    AVAssetWriterInput *assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio

                                                                               outputSettings:outputSettings]

                                            ;

    if ([assetWriter canAddInput:assetWriterInput]) {

        [assetWriter addInput:assetWriterInput];

    } else {

        NSLog (@"can't add asset writer input... die!");

        return;

    }

    

    assetWriterInput.expectsMediaDataInRealTime = NO;

    

    [assetWriter startWriting];

    [assetReader startReading];

    

    AVAssetTrack *soundTrack = [songAsset.tracks objectAtIndex:0];

    CMTime startTime = CMTimeMake (0, soundTrack.naturalTimeScale);

    [assetWriter startSessionAtSourceTime: startTime];

    

    __block UInt64 convertedByteCount = 0;

    

    dispatch_queue_t mediaInputQueue = dispatch_queue_create("mediaInputQueue", NULL);

    [assetWriterInput requestMediaDataWhenReadyOnQueue:mediaInputQueue

                                            usingBlock: ^

     {

         // NSLog (@"top of block");

         while (assetWriterInput.readyForMoreMediaData) {

             CMSampleBufferRef nextBuffer = [assetReaderOutput copyNextSampleBuffer];

             if (nextBuffer) {

                 // append buffer

                 [assetWriterInput appendSampleBuffer: nextBuffer];

                 //             NSLog (@"appended a buffer (%d bytes)",

                 //                    CMSampleBufferGetTotalSampleSize (nextBuffer));

                 convertedByteCount += CMSampleBufferGetTotalSampleSize (nextBuffer);

                 

                 

             } else {

                 // done!

                 [assetWriterInput markAsFinished];

                 [assetWriter finishWriting];

                 [assetReader cancelReading];

                 NSDictionary *outputFileAttributes = [[NSFileManager defaultManager]

                                                       attributesOfItemAtPath:exportPath

                                                       error:nil];

                 NSLog (@"done. file size is %lld",

                        [outputFileAttributes fileSize]);

                 

                 //创建caf文件结束,开始转换为mp3格式,然后发送给对方android手机

                 [self convertCAfToMp3:filename];

                 

                 // release a lot of stuff

//                 [assetReader release];

//                 [assetReaderOutput release];

//                 [assetWriter release];

//                 [assetWriterInput release];

//                 [exportPath release];

                 break;

             }

         }

         

     }];

}

- (void) convertMp3Finish

{

    NSLog(@"finish convert to mp3~");

}



// 将原始图片的URL转化为NSData数据,写入沙盒

- (void)imageWithUrl:(NSURL *)url withFileName:(NSString *)fileName

{

    NSString* KOriginalPhotoImagePath=[NSHomeDirectory() stringByAppendingFormat:@"/Documents/"] ;//stringByAppendingPathComponent:fileName];

    // 进这个方法的时候也应该加判断,如果已经转化了的就不要调用这个方法了

    // 如何判断已经转化了,通过是否存在文件路径

    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];

    // 创建存放原始图的文件夹--->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) {

            // 主要方法

            [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {

                ALAssetRepresentation *rep = [asset defaultRepresentation];

                unsigned long ssint=rep.size;

                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];

                

                //加入到selectedcontent

                CPSelectedContent *selContent= [[CPSelectedContent alloc]init];

                selContent.contentName=fileName;

                selContent.contentType=3;//5代表音乐

                selContent.contentSize=[[[NSFileManager defaultManager] attributesOfItemAtPath:imagePath error:nil] fileSize];

                NSLog(@"%ld",selContent.contentSize);

                

                selContent.contentUri=[[NSURL fileURLWithPath:imagePath ] absoluteString];

                selContent.diffField=_picNums;

                [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphonePicDatas setObject:selContent forKey:selContent.contentUri];

            } failureBlock:nil];

        }

    });

}


// 将原始视频的URL转化为NSData数据,写入沙盒

- (void)videoWithUrl:(NSURL *)url withFileName:(NSString *)fileName {

    NSString* KCachesPath=[NSHomeDirectory() stringByAppendingFormat:@"/Documents/"] ;

    

    // 解析一下,为什么视频不像图片一样一次性开辟本身大小的内存写入?

    // 想想,如果1个视频有1G,难道直接开辟1G多的空间大小来写?

    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        if (url) {

            [assetLibrary 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;

                    // 初始化一个1Mbuffer

                    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);//没到结尾,没出错,ok继续

                    }

                    // 释放缓冲区,关闭文件

                    free(buffer);

                    buffer = NULL;

                    fclose(file);

                    file = NULL;

                    //加入到selectedcontent

                    CPSelectedContent *selContent= [[CPSelectedContent alloc]init];

                    selContent.contentName=fileName ;

                    selContent.contentType=4;//5代表音乐

                    selContent.contentSize=[[[NSFileManager defaultManager] attributesOfItemAtPath:videoPath error:nil] fileSize];

                    NSLog(@"%ld",selContent.contentSize);

                    

                    selContent.contentUri=[[NSURL fileURLWithPath:videoPath ] absoluteString];

                    selContent.diffField=_videoNums;

                    [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneVideoDatas setObject:selContent forKey:selContent.contentUri];

                }

            } failureBlock:nil];

        }

    });

}


以下是具体连接其他手机建立热点的代码,同样也因为学识有限,还存在较多问题:

 BOOL iscontact=[self isConnectionAvailable] ;

    if (iscontact) {


        if ([@"172.20.10.1" isEqualToString:[self routerIp]]) {

            //iphone热点,这里更新界面

            NSString *strNickName=[self isCloneitAP:[self  currentWifiSSID]];

            

            if (strNickName==nil) {

                UIAlertView *myalert = [[UIAlertView alloc]

                                        initWithTitle:NSLocalizedString(@"连接新手机失败", @"连接的ios端热点不是一键换机建立的热点")

                                        message:NSLocalizedString(@"连接的android端热点不是一键换机建立的热点.请返回上一步之后重新连接.", nil)

                                        delegate:self

                                        cancelButtonTitle:NSLocalizedString(@"Cancel", @"Cancel")

                                        otherButtonTitles:nil];

                

                [myalert show];

            }else{

                

                self.vNewPhonePanel.hidden=false;

                self.lNewPhone.text=strNickName;

                [self.buttonConnectNP setEnabled:true];

            }


            

        }else if([@"192.168.43.1" isEqualToString:[self routerIp]])

        {

            //android热点,这里更新界面

            

            

            NSString *strNickName=[self isCloneitAP:[self  currentWifiSSID]];

            

            if (strNickName==nil) {

                UIAlertView *myalert = [[UIAlertView alloc]

                                        initWithTitle:NSLocalizedString(@"连接新手机失败", @"连接的android端热点不是一键换机建立的热点")

                                        message:NSLocalizedString(@"连接的android端热点不是一键换机建立的热点.请返回上一步之后重新连接.", nil)

                                        delegate:self

                                        cancelButtonTitle:NSLocalizedString(@"Cancel", @"Cancel")

                                        otherButtonTitles:nil];

                

                [myalert show];

            }else{

                

                self.vNewPhonePanel.hidden=false;

                self.lNewPhone.text=strNickName;

                [self.buttonConnectNP setEnabled:true];

            }

            

        }

        else {

            UIAlertView *myalert = [[UIAlertView alloc]

                                    initWithTitle:NSLocalizedString(@"连接新手机失败", @"连接的网络不是新手机热点")

                                    message:NSLocalizedString(@"连接的网络不是新手机热点.请返回上一步之后重新连接.", nil)

                                    delegate:self

                                    cancelButtonTitle:NSLocalizedString(@"Cancel", @"Cancel")

                                    otherButtonTitles:nil];

            

            [myalert show];

        }

        

        

    }else{

        UIAlertView *myalert = [[UIAlertView alloc]

                                initWithTitle:NSLocalizedString(@"连接新手机失败", @"网络连接失败")

                                message:NSLocalizedString(@"新手机未被连接.请返回上一步之后重新连接.", nil)

                                delegate:self

                                cancelButtonTitle:NSLocalizedString(@"Cancel", @"Cancel")

                                otherButtonTitles:nil];

        

        [myalert show];

        


    }

    

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


/*

#pragma mark - Navigation


// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

#pragma mark - 发送到新手机

- (IBAction)bConnectToNewPhone:(id)sender {

    

    //点击了之后就设置按钮不可用,避免被重复点击连接影响socket正常发送

    [self.buttonConnectNP setEnabled:false];

    //根据条件来判断最终发送给android端的内容是哪些。

    if ([CPDataSourceStatic sharedStaticDataSourceModle].isSendToNewphoneContactDatas) {

        [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas addEntriesFromDictionary:[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneContactDatas];

    }

    if ([CPDataSourceStatic sharedStaticDataSourceModle].isSendToNewphonePicDatas) {

        [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas addEntriesFromDictionary:[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphonePicDatas];

    }

    if ([CPDataSourceStatic sharedStaticDataSourceModle].isSendToNewphoneAudioDatas) {

        [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas addEntriesFromDictionary:[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneAudioDatas];

    }

    if ([CPDataSourceStatic sharedStaticDataSourceModle].isSendToNewphoneVideoDatas) {

        [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas addEntriesFromDictionary:[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneVideoDatas];

    }

    //创建socket发送给新手机,返回值为bool,用来判断是否发送成功

    BOOL issendSucceed=[self sendToNewPhone];

    

    

    

    

}

#pragma mark - socket相关

//判断socket是否连接新手机监听12345端口的socket成功

-(BOOL)isConnectToNewPhone{

    

    socket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

    NSError *err = nil;

    if(![socket connectToHost:@"192.168.43.1" onPort:[@"12345" intValue] error:&err])

    {

        NSLog(@"connect to new phone failed: %@",err.description);

        

        return false;

        

    }else

    {

        NSLog(@"connect to new phone succeed!");

        return  true;

    }

    

    

    

}

//连接到热点之后会回调

-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port

{

    NSLog(@"connect to new phone host: %@",host);

    [socket readDataWithTimeout:-1 tag:0];

}

//socket断开时出错

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err

{

     NSLog(@"socket had disconnect err: %@",err.description);

}



-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

{

    NSString *newMessage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"socket read data: %@%@",sock.connectedHost,newMessage);

   

    

}


//- (void)send:(id)sender {

//    [socket writeData:[message.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];

//    

//    [self addText:[NSString stringWithFormat:@":%@",message.text]];

//    [message resignFirstResponder];

//    [socket readDataWithTimeout:-1 tag:0];

//}



-(BOOL)sendToNewPhone{

    

    if(![self isConnectToNewPhone])

    {

        return false;

    }

    

    

    NSData *commonData=NULL;

    Byte databyte = MESSAGE_HEAD&0x00ff;

    

    int ss=sizeof(databyte);

    commonData = [NSData dataWithBytes: &databyte length: sizeof(databyte)];

    

    // commonData= [[NSData alloc] initWith:byte length:24];

    

    [socket writeData:commonData withTimeout:-1 tag:0];

    //发送文件数目

    int dataint= [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas count];

    //dataint= NSSwapHostIntToBig(dataint);

    

    //commonData = [NSData dataWithBytes: [self intToBytes:dataint] length: sizeof(dataint)];

    commonData = [NSData dataWithBytes: &dataint length: sizeof(dataint)];

    [socket writeData:commonData withTimeout:-1 tag:0];

    //发送文件总大小

    long long sumSize=0;

    int sstl=sizeof(sumSize);

    int sst=sizeof(dataint);

    

    

    

    for(id key in [CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas) {

        NSLog(@"key :%@  value :%@", key, [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas objectForKey:key]);

        CPSelectedContent *tmp= [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas objectForKey:key];

        sumSize+=tmp.contentSize;

    }

    sumSize=NSSwapHostLongLongToBig(sumSize);

    commonData = [NSData dataWithBytes: &sumSize length: sizeof(sumSize)];

    //commonData = [NSData dataWithBytes: [self longToBytes:sumSize] length: sizeof(sumSize)];

    [socket writeData:commonData withTimeout:-1 tag:0];

    

    //发送名字长度

    

    NSString *nickname=[[UIDevice currentDevice]name];

    //const char *sC = [nickname UTF8String];

    dataint=[self charNumber:nickname] ;

    commonData = [NSData dataWithBytes: &dataint length: sizeof(dataint)];

    [socket writeData:commonData withTimeout:-1 tag:0];

    //发送nickname ios固定为iphone本机别名

    commonData = [nickname dataUsingEncoding: NSUTF8StringEncoding];

    [socket writeData:commonData withTimeout:-1 tag:0];

    

    //发送mac地址这里暂时发送虚假的mac地址

    //dataint=0;

    NSString *macAddr=@"00:16:6d:3e:18:19";

    commonData = [macAddr dataUsingEncoding: NSUTF8StringEncoding];

    //commonData = [NSData dataWithBytes: &dataint length: 17];

    [socket writeData:commonData withTimeout:-1 tag:0];

    

    

    

    

    //分开发送每一个content

    for(id key in [CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas) {

        NSLog(@"key :%@  value :%@", key, [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas objectForKey:key]);

        CPSelectedContent *tmp= [[CPDataSourceStatic sharedStaticDataSourceModle].sendToNewphoneDatas objectForKey:key];

        [self sendContentToNewPhone:tmp];

    }

    

    RootViewController *mainViewController = [[RootViewController alloc] init];

    [self.navigationController pushViewController: mainViewController animated:true];

    //[mainViewController release];

    

    return  true;

}





-(BOOL)sendContentToNewPhone:(CPSelectedContent*) SelectedContent{

    CPSelectedContent *tmpSelectedContent=SelectedContent;

    NSData *commonData=NULL;

//发送文件属性

    Byte databyte=0;

    int dataint=0;

    databyte= MESSAGE_FILE_ATTRIBUTE&0x00ff;

    commonData = [NSData dataWithBytes: &databyte length: sizeof(databyte)];

    [socket writeData:commonData withTimeout:-1 tag:0];

    

    //发送url长度

    NSString *url=tmpSelectedContent.contentUri;

    databyte=[self charNumber:url] ;

    commonData = [NSData dataWithBytes: &databyte length: sizeof(databyte)];

    [socket writeData:commonData withTimeout:-1 tag:0];

    //发送url

    commonData = [url dataUsingEncoding: NSUTF8StringEncoding];

    [socket writeData:commonData withTimeout:-1 tag:0];

    //发送类型

    databyte=SelectedContent.contentType;

    commonData = [NSData dataWithBytes: &databyte length: sizeof(databyte)];

    [socket writeData:commonData withTimeout:-1 tag:0];

    

    //发送文件名长度

    NSString *filename=tmpSelectedContent.contentName;

    

    databyte=[self charNumber:filename] ;

    

    commonData = [NSData dataWithBytes: &databyte length: sizeof(databyte)];

    [socket writeData:commonData withTimeout:-1 tag:0];

    

    //发送文件名

    commonData = [filename dataUsingEncoding: NSUTF8StringEncoding];

    [socket writeData:commonData withTimeout:-1 tag:0];

    

    long long datalong=SelectedContent.contentSize;

    datalong=NSSwapHostLongLongToBig(datalong);

    commonData = [NSData dataWithBytes: &datalong length: sizeof(datalong)];

    [socket writeData:commonData withTimeout:-1 tag:0];

    

    

//发送文件内容

    databyte = MESSAGE_CONTENT&0x00ff;

    commonData = [NSData dataWithBytes: &databyte length: sizeof(databyte)];

    [socket writeData:commonData withTimeout:-1 tag:0];

    

    //NSURL *URL = [NSURL URLWithString:tmpSelectedContent.contentUri];

    NSData *dateFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:tmpSelectedContent.contentUri]];

    

    //NSMutableData *mutableData;

    //[mutableData appendData:(NSData *)dateFile];

    //这里注意,如果dateFile过大就需要分开发送

    [socket writeData:dateFile withTimeout:-1 tag:0];

    

    return true;

}


-(int)charNumber:(NSString*)strtemp {

    

    int strlength = 0;

    char* p = (char*)[strtemp cStringUsingEncoding:NSUTF8StringEncoding];

    for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUTF8StringEncoding] ;i++) {

        if (*p) {

            p++;

            strlength++;

        }

        else {

            p++;

        }

    }

    return strlength;

}

#pragma mark - 判断是否连接到网络

-(BOOL)isConnectionAvailable{


    BOOL isExistenceNetwork=YES;

        Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];

        switch ([reach currentReachabilityStatus]) {

                    case NotReachable:

                        isExistenceNetwork = NO;

                        //NSLog(@"notReachable");

                        break;

                    case ReachableViaWiFi:

                        isExistenceNetwork = YES;

                        //NSLog(@"WIFI");

                        break;

                    case ReachableViaWWAN:

                        isExistenceNetwork = NO;

                        //NSLog(@"3G");

                        break;

            }

    

        return isExistenceNetwork;  

}  



#pragma mark - 获取路由器地址

- (NSString *) routerIp {

    

    NSString *address = @"error";

    struct ifaddrs *interfaces = NULL;

    struct ifaddrs *temp_addr = NULL;

    int success = 0;

    

    

    // retrieve the current interfaces - returns 0 on success

    success = getifaddrs(&interfaces);

    if (success == 0)

    {

        // Loop through linked list of interfaces

        temp_addr = interfaces;

        //*/

        while(temp_addr != NULL)

        /*/

         int i=255;

         while((i--)>0)

         //*/

        {

            if(temp_addr->ifa_addr->sa_family == AF_INET)

            {

                // Check if interface is en0 which is the wifi connection on the iPhone

                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])

                {

                    // Get NSString from C String //ifa_addr

                    //ifa->ifa_dstaddr is the broadcast address, which explains the "255's"

                    //                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];

                    

                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];

                    

                    //routerIP----192.168.1.255 广播地址

                    NSLog(@"broadcast address--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)]);

                    //--192.168.1.106 本机地址

                    NSLog(@"local device ip--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]);

                    //--255.255.255.0 子网掩码地址

                    NSLog(@"netmask--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)]);

                    //--en0 端口地址

                    NSLog(@"interface--%@",[NSString stringWithUTF8String:temp_addr->ifa_name]);

                    

                }

                

            }

            

            temp_addr = temp_addr->ifa_next;

        }

    }

    

    // Free memory

    freeifaddrs(interfaces);

    

    

    

    in_addr_t i =inet_addr([address cStringUsingEncoding:NSUTF8StringEncoding]);

    in_addr_t* x =&i;

    

    

    unsigned char *s=getdefaultgateway(x);

    NSString *ip=[NSString stringWithFormat:@"%d.%d.%d.%d",s[0],s[1],s[2],s[3]];

    free(s);

    return ip;

}


#pragma mark - 获取wifi名称

- (NSString *)currentWifiSSID

{

    NSString *ssid = nil;

    NSArray *ifs = (__bridge   id)CNCopySupportedInterfaces();

    for (NSString *ifname in ifs) {

        NSDictionary *info = (__bridge id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifname);

        if ([info objectForKey:@"SSID"])

        {

            ssid = [info objectForKey:@"SSID"];

        }

    }

    

    return ssid;

}

#pragma mark - 判断是否是一键换机android端生成的ap

- (NSString*)isCloneitAP:(NSString*)str{

    

    //这里解析ssid转换为android端昵称

    NSString *tmp=str;

    return tmp;

}



- (id)fetchSSIDInfo {

    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();

    NSLog(@"Supported interfaces: %@", ifs);

    id info = nil;

    for (NSString *ifnam in ifs) {

        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);

        NSLog(@"%@ => %@", ifnam, info);

        if (info && [info count]) { break; }

    }

    return info;

}



// 将原始图片的URL转化为NSData数据,写入沙盒

- (void)imageWithUrl:(NSURL *)url withFileName:(NSString *)fileName

{

   NSString* KOriginalPhotoImagePath;

    // 进这个方法的时候也应该加判断,如果已经转化了的就不要调用这个方法了

    // 如何判断已经转化了,通过是否存在文件路径

    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];

    // 创建存放原始图的文件夹--->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) {

            // 主要方法

            [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];

        }

    });

}


// 将原始视频的URL转化为NSData数据,写入沙盒

- (void)videoWithUrl:(NSURL *)url withFileName:(NSString *)fileName withSocket: (GCDAsyncSocket*)socket_v

{

    NSString* KCachesPath;

    // 解析一下,为什么视频不像图片一样一次性开辟本身大小的内存写入?

    // 想想,如果1个视频有1G,难道直接开辟1G多的空间大小来写?

    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        if (url) {

            [assetLibrary 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;

                    // 初始化一个1Mbuffer

                    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);//没到结尾,没出错,ok继续

                    }

                    // 释放缓冲区,关闭文件

                    free(buffer);

                    buffer = NULL;

                    fclose(file);

                    file = NULL;

                }

            } failureBlock:nil];

        }

    });

}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值