STTwitterAPI to pull number of tweets,followers and following? - ios

I am trying to create a profile inside my application to show only his twitter profile. So far I do have the time line working but I don't have the number counter for the tweets,followers and following. I'm pretty sure I can use something what my code looks like but just don't know how, any help? Thanks
Code:
STTwitterAPI *twitter = [STTwitterAPI twitterAPIAppOnlyWithConsumerKey:#"ConsumerKey"
consumerSecret:#"consumerSecret"];
[twitter verifyCredentialsWithSuccessBlock:^(NSString *bearerToken) {
[twitter getUserTimelineWithScreenName:#"MikesiOSHelp"
successBlock:^(NSArray *statuses) {
self.twitterFeed = [NSMutableArray arrayWithArray:statuses];
[self->tableView reloadData];
} errorBlock:^(NSError *error) {
NSLog(#"%#", error.debugDescription);
}];
} errorBlock:^(NSError *error) {
NSLog(#"%#", error.debugDescription);
}];

You should check out their demo application.
Your request for finding the followers of a user is explicitly covered in the CLI demo:
typedef void (^AllFollowersBlock_t)(NSArray *allFollowers);
void getFollowers(STTwitterAPI *twitter,
NSString *screenName,
NSMutableArray *followers,
NSString *cursor,
AllFollowersBlock_t allFollowersBlock) {
if(followers == nil) followers = [NSMutableArray array];
NSMutableDictionary *md = [NSMutableDictionary dictionary];
md[#"screen_name"] = screenName;
if(cursor) md[#"cursor"] = cursor;
md[#"skip_status"] = #"1";
md[#"include_user_entities"] = #"0";
[twitter getResource:#"followers/list.json"
baseURLString:kBaseURLStringAPI_1_1
parameters:md
downloadProgressBlock:^(id json) {
//
} successBlock:^(NSDictionary *rateLimits, id response) {
NSArray *users = nil;
NSString *previousCursor = nil;
NSString *nextCursor = nil;
if([response isKindOfClass:[NSDictionary class]]) {
users = [response valueForKey:#"users"];
previousCursor = [response valueForKey:#"previous_cursor_str"];
nextCursor = [response valueForKey:#"next_cursor_str"];
}
NSLog(#"-- users: %#", #([users count]));
NSLog(#"-- previousCursor: %#", previousCursor);
NSLog(#"-- nextCursor: %#", nextCursor);
[followers addObjectsFromArray:users];
if([nextCursor integerValue] == 0) {
allFollowersBlock(followers);
return;
}
/**/
NSString *remainingString = [rateLimits objectForKey:#"x-rate-limit-remaining"];
NSString *resetString = [rateLimits objectForKey:#"x-rate-limit-reset"];
NSInteger remainingInteger = [remainingString integerValue];
NSInteger resetInteger = [resetString integerValue];
NSTimeInterval timeInterval = 0;
if(remainingInteger == 0) {
NSDate *resetDate = [[NSDate alloc] initWithTimeIntervalSince1970:resetInteger];
timeInterval = [resetDate timeIntervalSinceDate:[NSDate date]] + 5;
}
NSLog(#"-- wait for %# seconds", #(timeInterval));
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
getFollowers(twitter, screenName, followers, nextCursor, allFollowersBlock);
});
} errorBlock:^(NSError *error) {
NSLog(#"-- error: %#", error);
}];
}

Related

Is it possible to create a dispatch_async(dipatch_get_main_queue(), ^{}); with a completion go get when the dispatch block is finished?

I have a piece of code that execute a coredata update of the database, and I would like to know when that block is finished. Is there a way to get it knowing when the coredata has finished to update the tables?
Main function:
NSMutableArray* responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
dispatch_async(dispatch_get_main_queue(), ^{
[self parseAndAddLovAll:responseArray toArray:self.objects];
});
Function used in dispatch:
- (void)parseAndAddLovAll:(NSMutableArray*)responseArray toArray:(NSMutableArray*)destinationArray
{
NSError *error;
DB_ListOfValue_manage *elements_to_store = [[DB_ListOfValue_manage alloc] init];
NSManagedObjectContext * context = [elements_to_store managedObjectContext];
for (int index=0; index < [responseArray count]; index++)
{
NSDictionary * responseArray2 = [[NSDictionary alloc] initWithDictionary:responseArray[index]];
NSString * table_to_store = [[NSString alloc] initWithString:[responseArray2 objectForKey:#"table"]];
NSArray * lignes = [[NSArray alloc] initWithObjects:[responseArray2 objectForKey:#"lignes"], nil];
id value;
// Check if LOV table or contact table
if ((([#"Table_contact" compare:table_to_store])!=NSOrderedSame)&&
(([#"Table_event" compare:table_to_store])!=NSOrderedSame))
{
for (NSDictionary * item in lignes[0])
{
value = [item objectForKey:#"codeevent"];
if ([value isEqualToNumber:[NSNumber numberWithInt:EVENT_ID]])
{//FIXME: bug to check when SYNC
elements_to_store = (DB_ListOfValue_manage*)[NSEntityDescription insertNewObjectForEntityForName:table_to_store inManagedObjectContext:context];
elements_to_store.code_event = [value isKindOfClass:[NSNull class]] ? #"" : value;
value = [item objectForKey:#"id"];
elements_to_store.id = [value isKindOfClass:[NSNull class]] ? #"" : value;
value = [item objectForKey:#"used"];
elements_to_store.used = [value isKindOfClass:[NSNull class]] ? #"" : value;
if (![context save:&error]) {
#ifdef DEBUG
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
#endif
}
else{
#ifdef DEBUG
NSLog(#"Data saved to DB, table %# %# %#", table_to_store, elements_to_store.label1, elements_to_store.label2);
#endif
}
}
}
}
}
}

Sending token to back end stripe objective c

I can't seem to find the code to send my token to my firebase backend.
- (void)addCardViewController:(STPAddCardViewController *)addCardViewController didCreateToken:(STPToken *)token completion:(STPErrorBlock)completion {
[self submitTokenToBackend:token completion:^(NSError *error) {
if (error) {
completion(error);
} else {
[self dismissViewControllerAnimated:YES completion:^{
[self showReceiptPage];
}];
}
}];
}
Try this code,
STPAddress *address = [[STPAddress alloc] init];
address.name ="Test";
address.line1 = #"Test Address-1";
address.line2 = #"Test Address-2";
address.city = #"City";
address.postalCode = #"1234";
address.state = #"State";
address.country = #"Country";
STPCard *stripCard;
stripCard = [[STPCard alloc] init];
stripCard.number = strCard_Number;
stripCard.cvc = strCard_Cvv;
stripCard.expMonth = month;
stripCard.expYear = year;
stripCard.address = address;
stripCard.currency = #"INR";
[[STPAPIClient sharedClient] createTokenWithCard:stripCard completion:^(STPToken * _Nullable token, NSError * _Nullable error)
{
NSString *strMess= #"";
if(error) {
strMess = [error localizedDescription];
}
else {
strMess = stringValue(token.tokenId);
strMess = [NSString stringWithFormat:#"Token:\n-------\n%#\n\n\nCard Details:\n-------\n%#",strMess,token.allResponseFields];
//[Function showAlertMessage:strMess autoHide:NO];
NSString *strToken = #"";
strToken = token.tokenId;
NSLog(#"strToken: %#",strToken);
}
NSLog(#"strMess: %#",strMess);
}];

List contacts with phone numbers

I'd like to fetch (in iOS using Objective-C) only the contacts that have a phone number, but how can I do that? I'm trying to form the predicate as in the code below, but obviously that doesn't work.
contacts = [contactStore unifiedContactsMatchingPredicate:[NSPredicate predicateWithFormat:#"phoneNumbers <> nil"] keysToFetch:KEYS error:nil];
So, what is the correct way of doing this? Thanks for any help!
#import <Contacts/Contacts.h>
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
//keys with fetching properties
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactEmailAddressesKey];
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
request.sortOrder = CNContactSortOrderGivenName;
request.unifyResults = YES;
NSError *error;
__block NSString* email;
BOOL success = [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * __nonnull contact, BOOL * __nonnull stop)
{
if (error) {
NSLog(#"error fetching contacts %#", error);
} else {
NSString *fullName;
NSString* phone;
// for (CNContact *contact in cnContacts) {
DeviceContact *aContact = [DeviceContact new];
// copy data to my custom Contacts class.
NSString *firstName = contact.givenName;
NSString *lastName = contact.familyName;
if (lastName == nil) {
fullName=[NSString stringWithFormat:#"%#",firstName];
}else if (firstName == nil){
fullName=[NSString stringWithFormat:#"%#",lastName];
}
else{
fullName=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
if ([firstName trim].length > 0) {
aContact.nameForSorting = firstName; // 141116
}else if ([lastName trim].length>0 && aContact.nameForSorting.length<=0) {
aContact.nameForSorting = lastName; // 141116
}
aContact.name = fullName;
if (contact.phoneNumbers!=nil && [contact.phoneNumbers count]>0) {
for (CNLabeledValue *label in contact.phoneNumbers) {
phone = [CommonUtils removeAllSpecialCharactersFromPhoneNumber:[label.value stringValue]];
if ([phone length] > 0) {
[aContact.phoneNumber addObject:phone];
}
}
}
////Get all E-Mail addresses from contacts
/// if ([CommonUtils checkIsNullObject:[contact emailAddresses]] && [[contact emailAddresses] count]>0) {
for (CNLabeledValue *label in contact.emailAddresses) {
email = label.value;
if ([email length] > 0)
{
[aContact.email addObject:email];
}
}
// }
// 141116
if ([aContact.name trim].length <= 0) {
if (aContact.email.count>0) {
aContact.name = [aContact.email objectAtIndex:0];
}else if (aContact.phoneNumber.count>0){
aContact.name = [aContact.phoneNumber objectAtIndex:0];
}
}
if ([aContact.nameForSorting trim].length <= 0){
if (aContact.email.count>0) {
aContact.nameForSorting = [aContact.email objectAtIndex:0];
}else if (aContact.phoneNumber.count>0){
aContact.nameForSorting = [aContact.phoneNumber objectAtIndex:0];
}
}
[self.arrAllContacts addObject:aContact];
}
}];
if(success){
dispatch_async(dispatch_get_main_queue(), ^{
[CommonUtils hideLoader];
completionhandler(self.arrAllContacts);
});
}
}
else
{
// [CommonUtils showAlertMessageWithMessage:#"fdfdggfsgfdgfd" withDelegate:self withCancelTitle:OKAY isOtherButton:NO withOtherButtonTitle:nil withTag:0];
[CommonUtils hideLoader];
}
}];
use following method and import
#import <AddressBook/AddressBook.h>
#import <Contacts/Contacts.h>
-(void)contactsDetailsFromPhoneContactBook{
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
//keys with fetching properties
NSArray *keys = #[CNContactFamilyNameKey,CNContactGivenNameKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error) {
NSLog(#"error fetching contacts %#", error);
} else {
NSString *fullName;
NSString *firstName;
NSString *lastName;
for (CNContact *contact in cnContacts) {
// copy data to my custom Contacts class.
firstName = contact.givenName;
lastName = contact.familyName;
if (lastName == nil) {
fullName=[NSString stringWithFormat:#"%#",firstName];
}else if (firstName == nil){
fullName=[NSString stringWithFormat:#"%#",lastName];
}
else{
fullName=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
[self.contactsArray addObject:fullName];
NSLog(#"working or not %#",self.contactsArray);
}
}
}
}];
}
Filtering out the contacts that don't have a phone number (or some other property) is not possible. In the docs we read:
CNContact Predicates
Predicates to match contacts. You can only use these predicates
with CNContactStore and CNContactFetchRequest.
predicateForContactsMatchingName: Returns a predicate to find the contacts matching the specified name.
predicateForContactsWithIdentifiers: Returns a predicate to find the contacts matching the specified identifiers.
predicateForContactsInGroupWithIdentifier: Returns a predicate to find the contacts that are members in the specified group.
predicateForContactsInContainerWithIdentifier: Returns a predicate to find the contacts in the specified container.
And additionally:
Compound predicates are not supported.
So, the only way to do the filtering would be to omit adding to the result array the contacts with no phone numbers. That could be done, for example, in the block of the enumerateContactsWithFetchRequest.

EXC_BAD_ACCESS. Completion block

ANSWER
I heve a mistake when i call the fetchDailyForecast it should looks like
[self.fetchController fetchDailyForecast:self.currentLocation.coordinate completionBlock:^(DailyModel *newModel) {
_dailyCondition = newModel;
NSLog(#"newModel = %#", _dailyCondition);
}];
END
I try to use bloc's and wait but have a bad_access exaction. Firstly i call method from MangeDataController.m
[self.fetchController
fetchDailyForecast:self.currentLocation.coordinate
completionBlock:(void(^)(DailyModel *))_dailyCondition];
where the dailyCondition is instance of DailyModel.
Secondly here is fetchDailyForecast method realization in FetchController.m.
-(void)fetchDailyForecast:(CLLocationCoordinate2D)coordinate completionBlock:(void(^)(DailyModel *))completionBlock {
NSString *urlString = [NSString stringWithFormat:#"http://api.openweathermap.org/data/2.5/forecast/daily?lat=%f&lon=%f&units=imperial&cnt=7%#", coordinate.latitude, coordinate.longitude, _key];
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
[self fetchJSONfromURL:urlString completionBlock:^(NSDictionary *weatherData) {
completionBlock([[DailyModel alloc] dataFromDictionaryDaily:weatherData]); --- (here the bad access);
}];
}
and thirdly in fatchDailyForecast i call fetchJSONfromURL here is realization:
-(void)fetchJSONfromURL:(NSString *)urlString completionBlock:(void (^)(NSDictionary *))completionBlock {
NSLog(#"url = %#", urlString);
[_manager GET:urlString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responceObject) {
if (responceObject) {
completionBlock(responceObject);
} else {
NSLog(#"responce object error");
}
}
failure:^(NSURLSessionTask *operation, NSError *error){
NSLog(#"error %#", error);
}];
}
P.S. I think my mistake is that i try to pass day _dailyCondition but should pass something different. Thanks for any help!
**EDIT ------- DailyModel.m **
#import "DailyModel.h"
#implementation DailyModel
-(id)dataFromDictionaryDaily:(NSDictionary *)dic {
NSArray *arrayWithDictionarys = [dic objectForKey:#"list"];
NSDictionary *dictionaryWithWeekDays = [self indexKeyedDictionaryFromArray:arrayWithDictionarys];
// NSLog(#"dictionary with dayweeks = %#", dictionaryWithWeekDays);
_arrayWithTemp = [NSMutableArray new];
_arrayWithDate = [NSMutableArray new];
_arrayWithIcon = [NSMutableArray new];
for (int i = 0; i <= 6; i++) {
NSNumber* key = [NSNumber numberWithInt:i];
[self addValuesToArrayWithTemp:dictionaryWithWeekDays key:key index:i];
[self addValuesToArrayWithDate:dictionaryWithWeekDays key:key index:i];
[self addValueToArrayWithImage:dictionaryWithWeekDays key:key index:i];
}
return self;
}
- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array
{
NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
[array enumerateObjectsUsingBlock:
^(id obj, NSUInteger idx, BOOL *stop){
NSNumber *index = [NSNumber numberWithInteger:idx];
[mutableDictionary setObject:obj forKey:index];
}];
NSDictionary *result = [NSDictionary.alloc initWithDictionary:mutableDictionary];
return result;
}
-(void) addValuesToArrayWithTemp:(NSDictionary *)inputDic key:(NSNumber *)key index:(int)ind {
NSDictionary *currentDic = [inputDic objectForKey:key];
NSDictionary *temp = [currentDic objectForKey:#"temp"];
_tempLow = [temp objectForKey:#"min"];
_tempHigh = [temp objectForKey:#"max"];
_tempLow = [self convertToCelsius:_tempLow];
_tempHigh = [self convertToCelsius:_tempHigh];
NSString *tempString = [NSString stringWithFormat:#"%.02f / %.02f", _tempLow.floatValue , _tempHigh.floatValue];
[_arrayWithTemp insertObject:tempString atIndex:ind];
}
-(NSNumber *)convertToCelsius:(NSNumber *)far {
double f = (far.doubleValue - 32) / 1.8;
NSNumber *celsius = [NSNumber numberWithDouble:f];
return celsius;
}
-(void) addValuesToArrayWithDate:(NSDictionary *)inputDic key:(NSNumber *)key index:(int)ind {
NSDictionary *currenDic = [inputDic objectForKey:key];
NSNumber *tempNumber = [currenDic objectForKey:#"dt"];
double unixTimeStamp = tempNumber.doubleValue;
NSString* weekDay = [self convertToWeekDay:unixTimeStamp];
[_arrayWithDate insertObject:weekDay atIndex:ind];
}
-(NSString *)convertToWeekDay:(double) unixtime {
NSTimeInterval _interval = unixtime;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateFormat:#"EEEE"];
NSString *dateString = [formatter stringFromDate:date];
return dateString;
}
-(void) addValueToArrayWithImage:(NSDictionary *)inputDic key:(NSNumber *)key index:(int)ind {
NSDictionary *currenDic = [inputDic objectForKey:key];
NSArray *weatherArray = [currenDic objectForKey:#"weather"];
NSDictionary *weather = weatherArray[0];
_icon = [weather objectForKey:#"icon"];
_icon = [self currentImageString:_icon];
[_arrayWithIcon insertObject:_icon atIndex:ind];
}
-(NSString *)currentImageString:(NSString *)ico {
NSDictionary *dic = #{
#"01d" : #"weather-clear",
#"02d" : #"weather-few",
#"03d" : #"weather-few",
#"04d" : #"weather-broken",
#"09d" : #"weather-shower",
#"10d" : #"weather-rain",
#"11d" : #"weather-tstorm",
#"13d" : #"weather-snow",
#"50d" : #"weather-mist",
#"01n" : #"weather-moon",
#"02n" : #"weather-few-night",
#"03n" : #"weather-few-night",
#"04n" : #"weather-broken",
#"09n" : #"weather-shower",
#"10n" : #"weather-rain-night",
#"11n" : #"weather-tstorm",
#"13n" : #"weather-snow",
#"50n" : #"weather-mist",
};
ico = [dic objectForKey:ico];
return ico;
}
#end
EDIT 2
I add the condition into (void)fetchDailyForecast:(CLLocationCoordinate2D)coordinate completionBlock:(void(^)(DailyModel *))completionBlock and now app don't crash but it's still not work and nslog say #"nothing"
[self fetchJSONfromURL:urlString completionBlock:^(NSDictionary
*weatherData) { if (completionBlock) { completionBlock(model = [[DailyModel alloc] dataFromDictionaryDaily:weatherData]); } else {
NSLog(#"nothing"); } }];

Need to share songs with different devices using multipeer connectivity.

Requirement:
We are able to make connection from host device to multiple slave devices. For example, if device A initiate connection to device B and C, the contributor devices can accept peer connection and connected to device A. Here A is master device and B and C are contributors device. Now if B share their songs to A, A can play songs and see songs information. In meantime C will be idle but should connected. When B will finish to play songs, then C can also able to share their songs to device A.
Here are the problem that we have faced to achieve above tasks:
1. As soon as B started sharing songs to A, C got crashed. But A still able to play song shared by B.
array = [[NSMutableArray alloc] initWithObjects:[self.session connectedPeers], nil];
[_session sendData:[NSKeyedArchiver archivedDataWithRootObject:[info mutableCopy]] toPeers:[array objectAtIndex:0] withMode:MCSessionSendDataUnreliable error: &error];
NSLog(#"localizedDescription %#",error);
To overcome from this problem directly pass array without index here toPeers:array. It is working and we are able to share and play songs with device A, but song information not receive to device A.
Here are full code that we are using:
contributor Controller :
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
[self dismissViewControllerAnimated:YES completion:nil];
someMutableArray = [mediaItemCollection items];
counter = 0;
if(someMutableArray.count>1){
BOOL isselectsongone=YES;
[[NSUserDefaults standardUserDefaults] setBool:isselectsongone forKey:#"isselectsongone"];
}
[self showSpinner];
[self someSelector:nil];
}
- (void)someSelector:(NSNotification *)notification {
if(notification && someMutableArray.count>1 && counter <someMutableArray.count-1){
NSDate *start = [NSDate date];
counter=counter+1;
[self.outputStreamer stop];
self.outputStreamer = nil;
self.outputStream = nil;
}
song=[someMutableArray objectAtIndex:counter];
NSMutableDictionary *info = [NSMutableDictionary dictionary];
info=[[NSMutableDictionary alloc] init];
info[#"title"] = [song valueForProperty:MPMediaItemPropertyTitle] ? [song valueForProperty:MPMediaItemPropertyTitle] : #"";
info[#"artist"] = [song valueForProperty:MPMediaItemPropertyArtist] ? [song valueForProperty:MPMediaItemPropertyArtist] : #"";
//NSNumber *duration=[song valueForProperty:MPMediaItemPropertyPlaybackDuration];
int fullminutes = floor([timeinterval floatValue] / 60); // fullminutes is an int
int fullseconds = trunc([duration floatValue] - fullminutes * 60); // fullseconds is an int
[NSTimer scheduledTimerWithTimeInterval:[duration doubleValue]target:self selector:#selector(getdata) userInfo:nil repeats:YES];
}
-(void)getdata {
NSMutableDictionary *info = [NSMutableDictionary dictionary];
info=[[NSMutableDictionary alloc] init];
info[#"title"] = [song valueForProperty:MPMediaItemPropertyTitle] ? [song valueForProperty:MPMediaItemPropertyTitle] : #"";
info[#"artist"] = [song valueForProperty:MPMediaItemPropertyArtist] ? [song valueForProperty:MPMediaItemPropertyArtist] : #"";
NSNumber *duration=[song valueForProperty:MPMediaItemPropertyPlaybackDuration];
int fullminutes = floor([duration floatValue] / 60); // fullminutes is an int
int fullseconds = trunc([duration floatValue] - fullminutes * 60); // fullseconds is an int
info[#"duration"] = [NSString stringWithFormat:#"%d:%d", fullminutes, fullseconds];
MPMediaItemArtwork *artwork = [song valueForProperty:MPMediaItemPropertyArtwork];
UIImage *image = [artwork imageWithSize:CGSizeMake(150, 150)];
NSData * data = UIImageJPEGRepresentation(image, 0.0);
image = [UIImage imageWithData:data];
array = [[NSMutableArray alloc] initWithObjects:[self.session connectedPeers], nil];
MCPeerID* peerID11 = self.session.myPeerID;
NSMutableArray *arr=[[NSMutableArray alloc] initWithObjects:peerID11, nil];
NSLog(#"%#",arr);
if (image)
self.songArtWorkImageView.image = image;
else
self.songArtWorkImageView.image = nil;
self.songTitleLbl.text = [NSString stringWithFormat:#"%# \n[Artist : %#]", info[#"title"], info[#"artist"]];
NSError *error;
[_session sendData:[NSKeyedArchiver archivedDataWithRootObject:[info mutableCopy]] toPeers:[array objectAtIndex:0] withMode:MCSessionSendDataUnreliable error: &error];
NSLog(#"localizedDescription %#",error);
#try {
if(_session && _session.connectedPeers && [_session.connectedPeers count] > 0) {
NSLog(#"%#",[song valueForProperty:MPMediaItemPropertyAssetURL]);
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[song valueForProperty:MPMediaItemPropertyAssetURL] options:nil];
[self convertAsset: asset complition:^(BOOL Success, NSString *filePath) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
if(Success) {
if(image) {
[self saveImage: image withComplition:^(BOOL status, NSString *imageName, NSURL *imageURL) {
if(status) {
#try {
[_session sendResourceAtURL:imageURL withName:imageName toPeer:[_session.connectedPeers objectAtIndex:0]withCompletionHandler:^(NSError *error) {
if (error) {
NSLog(#"Failed to send picture to %#", error.localizedDescription);
return;
}
//Clean up the temp file
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtURL:imageURL error:nil];
}];
}
#catch (NSException *exception) {
}
}
}];
}
#try {
[self hideSpinner];
if(!self.outputStream) {
NSArray * connnectedPeers = [_session connectedPeers];
if([connnectedPeers count] != 0) {
[self outputStreamForPeer:[_session.connectedPeers objectAtIndex:0]];
}
}
}
#catch (NSException *exception) {
}
if(self.outputStream) {
self.outputStreamer = [[TDAudioOutputStreamer alloc] initWithOutputStream:self.outputStream];
//
[self.outputStreamer initStream:filePath];
NSLog(#"%#",filePath);
if(self.outputStreamer) {
[self.outputStreamer start];
}
else{
NSLog(#"Error: output streamer not found");
}
}
else{
//self.outputStream=[[NSOutputStream alloc] init];
self.outputStreamer = [[TDAudioOutputStreamer alloc] initWithOutputStream:self.outputStream];
[self.outputStreamer initStream:filePath];
NSLog(#"%#",filePath);
if(self.outputStreamer) {
[self.outputStreamer start];
}
}
}
else {
[UIView showMessageWithTitle:#"Error!" message:#"Error occured!" showInterval:1.5];
}
});
}];
// }
}
}
#catch (NSException *exception) {
NSLog(#"Expection: %#", [exception debugDescription]);
}
//}
}
HostViewcontroller :
- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID
{
NSLog(#"%#",peerID);
NSLog(#"sessions%#",session);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
#try {
// NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:data];
info = [NSKeyedUnarchiver unarchiveObjectWithData:data];
self.songTitleLbl.text = [NSString stringWithFormat:#"%# \n[Duration: %#] [Artist : %#] ", info[#"title"], info[#"duration"], info[#"artist"]];
NSLog(#"eeret%#",self.songTitleLbl.text);
self.songArtWorkImageView.image = nil;
[self showSpinner];
}
#catch (NSException *exception) {
self.songTitleLbl.text = #"Some error occured...\nPlease try again";
self.songArtWorkImageView.image = nil;
}
});
}
Please let us know if I have missed anything here or the better way to achieve the above requirement. Any help really appreciated.

Resources