I am using accept SDK for iOS in my project and its crashing with EXC_BAD_ACCESS
AcceptSDKHandler *handler = [[AcceptSDKHandler alloc] initWithEnvironment:AcceptSDKEnvironmentENV_TEST];
AcceptSDKRequest *request = [[AcceptSDKRequest alloc] init];
request.merchantAuthentication.name = #""; //name
request.merchantAuthentication.clientKey = #""; //clientkey
request.securePaymentContainerRequest.webCheckOutDataType.token.cardNumber = #""; //cardnumber
request.securePaymentContainerRequest.webCheckOutDataType.token.expirationMonth = #"";
request.securePaymentContainerRequest.webCheckOutDataType.token.expirationYear = #"";
request.securePaymentContainerRequest.webCheckOutDataType.token.cardCode = #"";
//crashing on below line
**[handler getTokenWithRequest:request successHandler:^(AcceptSDKTokenResponse * _Nonnull token)** {
NSLog(#"success %#", token.getOpaqueData.getDataValue);
} failureHandler:^(AcceptSDKErrorResponse * _Nonnull error) {
NSLog(#"failed... );
}];
Related
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);
}];
I'm trying to pass data from an NSMutableArray to an NSDictionary. It seems I do this successfully, however XCode throws me a crash when trying to display the passed data in self.username.text. Any idea why this is and how I can fix it? See code below.
ViewController.m
-(void)calloutTapped:(UITapGestureRecognizer *) sender
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
OtherUserViewController *yourViewController = (OtherUserViewController *)[storyboard instantiateViewControllerWithIdentifier:#"OtherUserViewController"];
NSDictionary *dictionary = [[NSDictionary alloc] init];
dictionary = [self.addressData mutableCopy];
yourViewController.mapuserData = dictionary;
[self.navigationController pushViewController:yourViewController animated:YES];
}
OtherUserViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
if (self.mapuserData != NULL) {
NSLog(#"This is map user data %#", self.mapuserData);
self.addFriend.hidden = NO;
self.username.text = self.mapuserData[#"users_name"];
NSLog(#"THIS IS IT %#", self.mapuserData[#"users_name"]);
self.userBio.text = self.mapuserData[#"userbio"];
NSString *thirdLink = self.mapuserData[#"photo_path"];
NSString *ImageURLTwo = thirdLink;
NSData *imageDataTwo = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURLTwo]];
self.userPhoto.image = [[UIImage alloc] initWithData:imageDataTwo];
}
if (neighbourDetail == NULL) {
self.addFriend.hidden = YES;
self.username.text = [self.myFriendData objectForKey:#"node_title"];
NSLog(#"this is friend detail %#", self.myFriendData);
self.userBio.text = [self.myFriendData objectForKey:#"body"];
NSString *thirdLink = [self.myFriendData objectForKey:#"friendphoto"];
NSString *ImageURLTwo = thirdLink;
NSData *imageDataTwo = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURLTwo]];
self.userPhoto.image = [[UIImage alloc] initWithData:imageDataTwo];
} else {
self.addFriend.hidden = NO;
self.username.text = [neighbourDetail objectForKey:#"first name"];
NSLog(#"this is neighbour detail %#", neighbourDetail);
self.userBio.text = [neighbourDetail objectForKey:#"userbio"];
NSString *secondLink = [neighbourDetail objectForKey:#"photo_path"];
NSString *ImageURL = secondLink;
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.userPhoto.image = [[UIImage alloc] initWithData:imageData];
}
NSString *testing = [self.myFriendData objectForKey:#"node_title"];
NSLog(#"This is the testing value %#", testing);
NSArray *friendorNo = self.checkfriendData;
NSLog(#"Friend or No Value %#", friendorNo);
for (NSDictionary *dict in friendorNo) {
if ([dict[#"node_title"] isEqualToString:testing]) {
self.addFriend.hidden = YES;
}
}
Logged data passed succesfully to self.mapuserData:
2017-06-14 22:03:49.397526-0700[3706:1178771] This is user data (
{
address = "2957 chill street";
childrenunder = Yes;
city = Vancouver;
"emergency facility" = None;
"first name" = josh;
"last name" = tree;
phone = 688;
"photo_path" = "x.png";
"points balance" = 24;
"postal code" = b6b6v5;
"profile photo" = "<null>";
"property type" = Apartment;
province = ont;
"special skills" = "None";
"star rating" = 0;
"street_address" = none;
supervision = Yes;
uid = 182;
userbio = nfkkdkckmfkekxkx;
"users_name" = "josh_tree#hotmail.com";
}
You are accessing an array.
Can you try this:
_username.text = [self.mapuserData firstObject][#"users_name"]
So, basically self.mapUserContent is an array of dictionary. What we did is get the first object and from the first object we get the username.
let me know if this works
You are trying to call objectForKey: for NSArray object.
self.addressData is a kind of NSArray
FIX:
NSDictionary *dictionary = [[NSDictionary alloc] init];
dictionary = [[self.addressData firstObject] mutableCopy];
yourViewController.mapuserData = dictionary;
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"); } }];
I'm using JSQMessage and am having a little difficulty with showing the placeholder for media until I have it correctly downloading, and then replacing with the media. I have everything working correctly as far as adding the messages and media to server, I just can't get it to replace the placeholders.
Currently, I have a function that queries my database and pulls an array of objects for messages and then loops through and calls this function for each object to output and add it to my message thread. I'm struggling to figure out why the section with "messageToAdd.isMediaMessage" is not replacing the placeholders with the actual media following it's download from the server. Does anyone know how I should be handling this to make sure it adds the message with a placeholder, and then replaces once the media is downloaded correctly?
- (void)addMessage:(PFObject *)object
{
id<JSQMessageMediaData> messageMedia = nil;
PFObject *user = object[#"messageSender"];
[users addObject:user];
NSString *name = #"";
if(user[#"profileFName"] && user[#"profileLName"])
name= [NSString stringWithFormat:#"%# %#",user[#"profileFName"],user[#"profileLName"]];
else
name= [NSString stringWithFormat:#"%# %#",user[#"consultantFName"],user[#"consultantLName"]];
if([object[#"messageFileType"] isEqual: #"video"]){
JSQVideoMediaItem *messageMedia = [[JSQVideoMediaItem alloc] init];
messageMedia.fileURL = nil;
messageMedia.isReadyToPlay = NO;
messageToAdd = [JSQMessage messageWithSenderId:user.objectId displayName:name media:messageMedia];
} else if ([object[#"messageFileType"] isEqual: #"image"]){
JSQPhotoMediaItem *messageMedia = [[JSQPhotoMediaItem alloc] init];
messageMedia.image = nil;
messageToAdd = [JSQMessage messageWithSenderId:user.objectId displayName:name media:messageMedia];
} else{
messageToAdd= [[JSQMessage alloc] initWithSenderId:user.objectId senderDisplayName:name date:object[#"sendDate"] text:object[#"messageContent"]];
}
if(isLoadMore)
[messages insertObject:messageToAdd atIndex:0];
else
[messages addObject:messageToAdd];
// NOT TRIGGERING THESE AFTER MEDIA DOWNLOADED
if (messageToAdd.isMediaMessage) {
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
if ([object[#"messageFileType"] isEqual: #"image"]){
[object[#"messageMedia"] getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
if (!error) {
JSQPhotoMediaItem *photoItem = [[JSQPhotoMediaItem alloc] initWithImage:[UIImage imageWithData:imageData]];
((JSQPhotoMediaItem *)messageMedia).image = [UIImage imageWithCGImage:photoItem.image.CGImage];
[self.collectionView reloadData];
}
}];
}
else if([object[#"messageFileType"] isEqual: #"video"]){
PFFile *videoFile = object[#"messageMedia"];
NSURL *videoURL = [NSURL URLWithString:videoFile.url];
((JSQVideoMediaItem *)messageMedia).fileURL = videoURL;
((JSQVideoMediaItem *)messageMedia).isReadyToPlay = YES;
[self.collectionView reloadData];
}
else {
NSLog(#"%s error: unrecognized media item", __PRETTY_FUNCTION__);
}
});
}
}
For others who come along with the same issue/question, I resolved how it was working by looking at the project NotificationChat here:https://github.com/relatedcode/NotificationChat/blob/master/NotificationChat/Classes/Chat/ChatView.m. It gives a really good overview of using the JSQMessage platform.
Here's my modified function so you can see the finished product.
- (void)addMessage:(PFObject *)object
{
PFObject *user = object[#"messageSender"];
[users addObject:user];
PFFile *mediaMessage = object[#"messageMedia"];
NSString *name = #"";
if(user[#"profileFName"] && user[#"profileLName"])
name= [NSString stringWithFormat:#"%# %#",user[#"profileFName"],user[#"profileLName"]];
else
name= [NSString stringWithFormat:#"%# %#",user[#"consultantFName"],user[#"consultantLName"]];
if([object[#"messageFileType"] isEqual: #"video"]){
JSQVideoMediaItem *mediaItem = [[JSQVideoMediaItem alloc] initWithFileURL:[NSURL URLWithString:mediaMessage.url] isReadyToPlay:YES];
mediaItem.appliesMediaViewMaskAsOutgoing = [user.objectId isEqualToString:self.senderId];
messageToAdd = [[JSQMessage alloc] initWithSenderId:user.objectId senderDisplayName:name date:object.createdAt media:mediaItem];
} else if ([object[#"messageFileType"] isEqual: #"image"]){
JSQPhotoMediaItem *mediaItem = [[JSQPhotoMediaItem alloc] initWithImage:nil];
mediaItem.appliesMediaViewMaskAsOutgoing = [user.objectId isEqualToString:self.senderId];
messageToAdd = [[JSQMessage alloc] initWithSenderId:user.objectId senderDisplayName:name date:object.createdAt media:mediaItem];
[mediaMessage getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error)
{
if (error == nil)
{
mediaItem.image = [UIImage imageWithData:imageData];
[self.collectionView reloadData];
}
}];
} else{
messageToAdd= [[JSQMessage alloc] initWithSenderId:user.objectId senderDisplayName:name date:object[#"sendDate"] text:object[#"messageContent"]];
}
if(isLoadMore)
[messages insertObject:messageToAdd atIndex:0];
else
[messages addObject:messageToAdd];
}
Based on the code I think one possible reason is you need reloadData on main(UI) thread after download data successfully and asynchronously on background thread
I want to publish an Open Graph fitness:runs action on Facebook and I want it to render with a map of my path. The path is defined by the path coordinates below. How do I do this? The method below publishes the action and I can see the text for the action in my Activity Log on Facebook and in my timeline. But I do not see a map when I hoover over any element of the posted action. What am I doing wrong?
- (void) fbPost:(NSString *)txt toList:(NSString *)listId { // post
[FBSession setActiveSession:[FacebookManager instance].facebook.session];
NSMutableDictionary<FBGraphObject> *action = [FBGraphObject graphObject];
action[#"course"] = #"http://samples.ogp.me/48586838281818";
action[#"privacy"] = privacyStr;
NSMutableArray *coords = [NSMutableArray arrayWithCapacity:59];
for (int i = 0; i < 59; i++)
{
NSMutableDictionary *coord = [[NSMutableDictionary alloc] initWithCapacity:3];
#define TIMESTAMP #"fitness:metrics:timestamp"
#define LATITUDE #"fitness:metrics:location:latitude"
#define LONGITUDE #"fitness:metrics:location:longitude"
[coord setValue:[NSString stringWithFormat:#"2013-04-01T12:%2d:00+0000", i] forKey:TIMESTAMP];
[coord setValue:[NSString stringWithFormat:#"%f", 37.442564 + i * 0.00001] forKey:LATITUDE];
[coord setValue:[NSString stringWithFormat:#"%f", -122.164879 + i * 0.000001] forKey:LONGITUDE];
[coords addObject:coord];
NSLog(#"coord=%# i=%d", coord, i);
}
action[#"path"] = [coords JSONString];
action[#"message"] = txt;
[FBRequestConnection startForPostWithGraphPath:#"me/fitness.runs"
graphObject:action
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if (!error) // it's a post, save id
{
}
else
{
}
}];
}
NSMutableDictionary<FBGraphObject> *action = [FBGraphObject graphObject];
NSMutableDictionary<FBGraphObject> *course = [FBGraphObject openGraphObjectForPost];
course[#"og:title"] = #"My Workout";
course[#"og:type"] = #"fitness.course"; //very important
course[#"og:url"] = #"www.fitness.com"; // give a meaningful url here
course[#"fitness:duration:value"] = #"3000";
course[#"fitness:duration:units"] = #"s";
course[#"fitness:calories"] = #"100";
course[#"fitness:distance:value"] = 1.7;
course[#"fitness:distance:units"] = #"mi";
course[#"fitness:speed:value"] = #"2";
course[#"fitness:speed:units"] = #"m/s";
course[#"fitness:pace:value"] = #"0.5";
course[#"fitness:pace:units"] = #"s/m";
course[#"og:description"] = #"course_description";
NSMutableArray *locationDataPointsArray = [[NSMutableArray alloc] init];
locationDataPointsArray[0] = #{#"location:latitude": 12.91277, #"location:longitude": 77.56671};
locationDataPointsArray[1] = #{#"location:latitude": 12.91284, #"location:longitude": 77.56681};
locationDataPointsArray[2] = #{#"location:latitude": 12.91297, #"location:longitude": 77.56691};
course[#"fitness:metrics"] = locationDataPointsArray;
action[#"fb:explicitly_shared"] = #"true";
action[#"course"] = course;
NSString *path = #”me/fitness.runs”;
//for custom story: NSString *path = #”me/urNamespace:name of ur action”;
[FBRequestConnection startForPostWithGraphPath:path graphObject:action completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"Posted fitness action, id: %#", [result objectForKey:#"id"]);
NSString *alertText = #"Workout successfully posted to Facebook :)";
NSString *alertTitle = #"Success";
[[[UIAlertView alloc] initWithTitle:alertTitle message:alertText delegate:nil cancelButtonTitle:#"OK!" otherButtonTitles:nil] show];
}
else {
NSLog(#"error in posting action %#", error.description);
}
}];
I don't really know how to answer you question however I read some documents the other day and they may be useful to you...
I would Recommend
That you take a read of this document and hopefully you will be able to understand how to integrate this in your app.
You may also want to take a read of this
& this
Happy coding :)