In my iOS app I'm using the weather APIs of worldweatheronline.com but I get a random "EXC_BAD_ACCESS" error oh this row (not always but sometimes) :
temperature.text = [NSString stringWithFormat:#"%# °C", tempC];
Here is my code:
- (void)showWeatherFor:(CLLocation *)newLocation
{
NSString *myRequestString = [[NSString alloc] initWithFormat:#"http://api.worldweatheronline.com/free/v1/weather.ashx?q=%f,%f&format=json&num_of_days=5&key=ydvgep8jn5m846upd8kb2qp6", newLocation.coordinate.latitude, newLocation.coordinate.longitude];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:myRequestString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *JsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *theDictionary = [NSDictionary dictionaryWithJSONString:JsonString error:&error];
NSDictionary *data = [theDictionary objectForKey:#"data"];
NSArray *currentDictionary = [data objectForKey:#"current_condition"];
NSDictionary *temp = [currentDictionary objectAtIndex:0];
if ([temp objectForKey:#"temp_C"] == nil || [temp objectForKey:#"temp_F"] == nil)
{
return;
termometro.alpha = 0;
}
else
{
if (temp != nil)
{
if ([mainDelegate.gradi isEqualToString: #"°C"])
{
NSNumber *tempC = [temp objectForKey:#"temp_C"];
temperature.text = [NSString stringWithFormat:#"%# °C", tempC];
mainDelegate.temperature = [[temp objectForKey:#"temp_C"]intValue];
}
else
{
NSNumber *tempF = [temp objectForKey:#"temp_F"];
temperature.text = [NSString stringWithFormat:#"%# °F", tempF];
mainDelegate.temperature = [[temp objectForKey:#"temp_F"]intValue];
}
termometro.alpha = 1;
}
}
}
Related
When i got my server response and trying to save that in plist, but plist file is not creating.
I have logged file path and dictionary contents but all these have data still plist not creating
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self sideMenu:#"ML"];
return YES;
}
this will call following method
-(void)sideMenu:(NSString *)title{
NSString *myRequestString = [[NSString alloc] initWithFormat:#"data=%#&deviceid=e8ef8c98262185ec",title];
NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String ] length: [ myRequestString length ] ];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:SIDE_MENU]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: myRequestData];
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];
NSString* responseString = [[NSString alloc] initWithData:returnData encoding:NSNonLossyASCIIStringEncoding];
NSArray *myArray = [responseString componentsSeparatedByString:#"<!DOC"];
//NSLog(#"%#",myArray);
if (myArray != nil || [myArray count] > 0) {
NSData *data = [[[myArray objectAtIndex:0]stringByReplacingOccurrencesOfString:#"\n" withString:#""] dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[self sideMenuFile:title :json];
}
}
-(NSString *)sideMenuFile:(NSString *)titleName :(NSDictionary *)dict{
NSString *filePath;
MyManager *sharedManager =[MyManager sharedManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if([titleName isEqualToString:#"ML"])
{ sharedManager.sideMenu = [[NSDictionary alloc]init];
sharedManager.sideMenu = dict;
filePath = [documentsDirectory stringByAppendingPathComponent:#"ML.plist"];
}else if ([titleName isEqualToString:#"HM"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"HM.plist"];
}else if ([titleName isEqualToString:#"PDC"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"PDC.plist"];
}else if ([titleName isEqualToString:#"SM"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"SM.plist"];
}else if ([titleName isEqualToString:#"GL"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"GL.plist"];
}else if ([titleName isEqualToString:#"CU"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"CU.plist"];
}else if ([titleName isEqualToString:#"BR"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"GL.plist"];
}
NSLog(#"%#",filePath); //printing path
[dict writeToFile:filePath atomically:YES];
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *plistName = #"GL";
NSString *finalPath = [basePath stringByAppendingPathComponent:
[NSString stringWithFormat: #"%#.plist", plistName]];
NSDictionary *dictww=[[NSDictionary alloc]initWithContentsOfFile:finalPath];
NSLog(#"dict%#",dictww); //printing nill
return filePath;
}
JSON file structure
{
sigallery = {
rows = (
{
active = True;
gallerytext = "<null>";
galleryurl = "assets/img/content-images/1.jpg";
moddt = "2016-07-19T12:28:18.873";
onclickurl = "testd.in";
settingsid = 1;
showfromdt = "1901-01-01T00:00:00.0";
showsequence = 1;
showuptodt = "2099-12-31T00:00:00.0";
videoimagebanneraudioswitch = I;
},
{
active = True;
gallerytext = "<null>";
galleryurl = "assets/img/content-images/2.jpg";
moddt = "2016-07-19T12:28:18.873";
onclickurl = "testd.in";
settingsid = 1;
showfromdt = "1901-01-01T00:00:00.0";
showsequence = 2;
showuptodt = "2099-12-31T00:00:00.0";
videoimagebanneraudioswitch = I;
}
)
}
}
Your code makes a number of non-optimal assumptions.
1)
Whenever you write out a file, you should always check for any error condition if it's available. NSDictionary's writeTo... methods do return Booleans whether the file has been written out or not, so you could do:
NSLog(#"%#",filePath); //printing path
BOOL success = [dict writeToFile:filePath atomically:YES];
if (success == false)
{
NSLog(#"did not successfully write dictionary to path %#", filePath);
} else {
// ... do everything else in here
}
2)
You write out files wih the format titleName + GL | PDC | SM.plist but when you try to read things back in, there is no titleName as part of the finalPath, so nothing lines up here.
3)
Also, why do you assume basePath is valid (it looks like it could be nil)?
Basically I got response from server side and then i saved it in local file.Actually I fetched the response from server side and then saved into documents directory ,and now trying to fetch but it comes in NSString only ,i unable to get in NSDictionary....Here is following code
- (IBAction)loginButtonPressed:(id)sender
{
NSString *URLString = #"http://localhost/rest/login";
AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *params = #{#"username": userNameTxtField.text, #"password": pwdTextField.text};
NSLog(#"Parameters:\n%#",params);
[manager POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask *operation, id responseObject)
{
NSLog(#"Successfully Login ....: %#", responseObject);
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [NSString stringWithFormat:#"%#/sample.json", documents];
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:path append:YES];
[stream open];
NSError *writeError = nil;
NSInteger bytesWritten = [NSJSONSerialization writeJSONObject:responseObject toStream:stream options:NSJSONWritingPrettyPrinted error:&writeError];
if ((bytesWritten = 0))
{
NSLog(#"Error writing JSON Data");
}
else{
NSLog(#"Sucessfuly saved data...");
}
[stream close];
NSLog(#"path is :%#",path);
} failure:^(NSURLSessionDataTask *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
- (IBAction)fetch:(id)sender
{
NSError *deserializingError;
NSData *data=[NSData dataWithContentsOfFile:path];
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&deserializingError];
NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"vaues are:%#",dict);
}
Your response object should be a type of NSDictionary. Therefore you can use its writeToFileAtPath method to save it to your documents directory.
When recreating the dictionary, you can use the NSDictionary's alloc and initWithContentsOfFile method to directly create a NSDictionary instance.
There are tons of posts on how to do that if you do a little Google search!
Try this!! It's working fine.
NSMutableDictionary *testStore = [[NSMutableDictionary alloc] init];
[testStore setObject:#"vignesh" forKey:#"username"];
[testStore setObject:#"password" forKey:#"password"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:testStore // Here you can pass array or dictionary
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSString *jsonString;
if (jsonData) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//This is your JSON String
//NSUTF8StringEncoding encodes special characters using an escaping scheme
} else {
NSLog(#"Got an error: %#", error);
jsonString = #"";
}
[self writeStringToFile:jsonString];
NSLog(#"Your JSON String is %#", [self readStringFromFile]);
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
// Write to file
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
- (NSString*)readStringFromFile {
// Build the path...
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
// read from file
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
static const char *dbPath = nil;
static sqlite3_stmt *ermsg = nil;
static sqlite3 *studs =nil;
static DatabaseOperation *_sharedInstances = nil;
#implementation DatabaseOperation
#synthesize databasePath;
+(DatabaseOperation*)sharedInstances{
if(!_sharedInstances){
_sharedInstances =[[super allocWithZone:nil]init];
}
return _sharedInstances;
}
+(id)allocWithZone:(struct _NSZone *)zone{
return [self sharedInstances];
}
-(id)init{
NSLog(#"Only first time Instances using Singleton:");
self =[super init];
if(self){
[self CreateDbpath];
}
return self;
}
-(BOOL)CreateDbpath{
NSArray *dbpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docdir=[[NSString alloc]initWithString:[dbpaths objectAtIndex:0]];
self.databasePath =[[NSString alloc]initWithString:[docdir stringByAppendingPathComponent:#"Mindset.sqlite"]];
NSFileManager *flg = [NSFileManager defaultManager];
BOOL isSuccess = false;
if([flg fileExistsAtPath:databasePath]==NO){
char *ermsgss = nil;
char const *dbpathss =[self.databasePath UTF8String];
if(sqlite3_open(dbpathss, &studs)==SQLITE_OK){
char *sqlQuery ="create table if not exists emp(name text,city text,img blob)";
if(sqlite3_exec(studs, sqlQuery, nil, nil, &ermsgss)!=SQLITE_OK){
NSLog(#"Failed to create table:");
}
else{
NSLog(#"Successfully to create table:");
}
}
sqlite3_close(studs);
}
return isSuccess;
}
-(void)insertDatabaseValue:(DataManagers *)getInserted{
dbPath = [self.databasePath UTF8String];
if(sqlite3_open(dbPath, &studs)==SQLITE_OK){
NSString *sqlQuery=[[NSString alloc]initWithFormat:#"insert into emp values(?,?,?)"];
const char *_sqlQuery=[sqlQuery UTF8String];
if(sqlite3_prepare_v2(studs, _sqlQuery, -1, &ermsg, nil)==SQLITE_OK){
sqlite3_bind_text(ermsg, 1, [getInserted.userName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(ermsg, 2, [getInserted.cityName UTF8String], -1, SQLITE_TRANSIENT);
NSData *jpegData =[[NSData alloc]init];
NSData *imgeData =UIImageJPEGRepresentation(getInserted.profileImg, 0.85f);
UIImage *imgesData =[UIImage imageWithData:imgeData];
CGRect rect = CGRectMake(0, 0, 185, 150);
UIGraphicsBeginImageContext(rect.size);
[imgesData drawInRect:rect];
UIImage *img =UIGraphicsGetImageFromCurrentImageContext()
;
UIGraphicsEndImageContext();
jpegData = UIImageJPEGRepresentation(img, 0.01f);
sqlite3_bind_blob(ermsg, 3, [jpegData bytes], [jpegData length], SQLITE_TRANSIENT);
if(sqlite3_step(ermsg)==SQLITE_DONE){
NSLog(#"Successfully inserted into db:");
}
else {
NSLog(#"Error %s",sqlite3_errmsg(studs));
}
}
sqlite3_close(studs);
sqlite3_finalize(ermsg);
}
}
-(NSMutableArray*)getAllData {
NSMutableArray *array =[[NSMutableArray alloc]init];
dbPath = [self.databasePath UTF8String];
if(sqlite3_open(dbPath, &studs)==SQLITE_OK){
NSString *sqlQuery =[[NSString alloc]initWithFormat:#"select * from emp"];
const char *_sqlQuery =[sqlQuery UTF8String];
if(sqlite3_prepare_v2(studs, _sqlQuery, -1, &ermsg, nil)==SQLITE_OK){
while (sqlite3_step(ermsg)==SQLITE_ROW) {
DataManagers *mgr =[[DataManagers alloc]init];
NSString *_Firstname = (const char*)sqlite3_column_text(ermsg, 0) ? [NSString stringWithUTF8String:(const char*)sqlite3_column_text(ermsg, 0)]:nil;
mgr.userName = _Firstname;
NSString *lastName =(const char*)sqlite3_column_text(ermsg, 1)?[NSString stringWithUTF8String:(const char*)sqlite3_column_text(ermsg, 1)]:nil;
mgr.cityName = lastName;
int imgBytes = sqlite3_column_bytes(ermsg, 2);
UIImage *img =[UIImage imageWithData:[NSData dataWithBytes:sqlite3_column_blob(ermsg, 2) length:imgBytes]];
mgr.profileImg = img;
[array addObject:mgr];
}
}
}
return array;
}
I had some data in my UITableView with four labels (Project,tasks, subtasks and hours), I changed my data from the backend (going to database and changed the data). I changed number of hours from 12 to 10. But I was only seeing the old data (12 hours instead of 10 hours) in my UITableView. Can any one suggest what is the reason behind that. I tried to clean, restart the computer which doesn't load the correct data that is in database. Other thing I can add is I was retrieving the data with the help of web service. and converting the data from JSONSerialization format to NSArray. When I ping my web service in browser URL, it gives me the correct data. Here is the below code :
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadprojects];
}
NSString *strwebsite = [[NSUserDefaults standardUserDefaults] valueForKey:#"website"];
NSString *websitemethods = #"Timesheet.svc/GetTimesheet";
NSString *projecturltemp = [strwebsite stringByAppendingString:websitemethods];
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * projecturl =[NSString stringWithFormat:#"%#/%#/%#",projecturltemp,usrid,eventDate];
NSURL *url = [NSURL URLWithString:projecturl];
[self.tableView reloadData];
NSLog(#"url : %#", url);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//NSLog(#"urlData : %#",urlData);
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseDatatest = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments error:&error];
NSLog(#"responseDatatest : %#",responseDatatest);
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseDatatest dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
NSLog(#"Entries : %#", entries);
if(!entries)
{
NSLog(#"Error : %#", error);
}
else{
for (NSDictionary *entry in entries) {
projectNames = [entries valueForKey:#"NM_PROJECT"];
taskNames = [entries valueForKey:#"TASk_NAME"];
subtaskNames = [entries valueForKey:#"SUBTASK_NAME"];
timesheetid = [entries valueForKey:#"ID_TIMESHEET_DTLS"];
projId = [entries valueForKey:#"ID_PROJECT"];
taskId = [entries valueForKey:#"ID_TASK"];
subtaskId = [entries valueForKey:#"ID_SUB_TASK"];
totalhours = [entries valueForKey:#"No_Hours"];
approve = [entries valueForKey:#"FL_APPROVE"];
leaves = [entries valueForKey:#"NM_LEAVE"];
}
}
} else {
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [projectNames count];
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identitifier = #"Cell";
TableViewCell * cell = [tableView
dequeueReusableCellWithIdentifier:identitifier
forIndexPath:indexPath];
if ([[[timesheetid objectAtIndex:indexPath.row] stringValue] isEqualToString:#"0"])
{
cell.lblProjects.text = [NSString stringWithFormat:#"%#",#"No Projects Filled"];
cell.lblTasks.text = [NSString stringWithFormat:#"%#",#"No Tasks Filled"];
cell.lblSubTasks.text = [NSString stringWithFormat:#"%#",#"No SubTasks Filled"];
cell.lblHours.text = [NSString stringWithFormat:#"%#",#"0 Hours Filled"];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
else if ([[leaves objectAtIndex:indexPath.row] isEqualToString:#"0"])
{
cell.lblProjects.text = [projectNames objectAtIndex:indexPath.row];
cell.lblTasks.text = [taskNames objectAtIndex:indexPath.row];
cell.lblSubTasks.text = [subtaskNames objectAtIndex:indexPath.row];
cell.lblHours.text = [[totalhours objectAtIndex:indexPath.row] stringValue];
//NSLog(#"cell :%#",cell.lblHours.text);
}
else
{
cell.lblProjects.text = [leaves objectAtIndex:indexPath.row];
cell.lblTasks.text = [NSString stringWithFormat:#"%#",#"No Projects/Tasks on this Date"];
cell.lblSubTasks.text = [NSString stringWithFormat:#"%#",#"No Sub Tasks on this Date"];
cell.lblHours.text = [[totalhours objectAtIndex:indexPath.row] stringValue];
}
cell.editingAccessoryType = UITableViewCellAccessoryDetailDisclosureButton;
NSNumber *myProjectArrayString = [timesheetid objectAtIndex:indexPath.row];
cell.hdbrowcount = [NSString stringWithFormat:#"%#",myProjectArrayString];
return cell;
}
I don't see this line
[self.tableview reloadData];
use postnotification whenever change data.
[[NSNotificationCenter defaultCenter] postNotificationName:#"refresh" object:self];
In this method:
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;
NSURL *videoURL = [self videoURLWithData:self.connectionData error:&error];
if (videoURL)
self.moviePlayer.contentURL = videoURL;
else if (self.elFields.count > 0)
[self startVideoInfoRequest];
else
[self finishWithError:error];
}
videoURL is returned as nil and hence, it is going to the error block. Youtube video id that I am using is "5Uls9v1nnss". What seems to be the issue?
the videoURLWithData method which is used to retrieve the videoURL is this :
- (NSURL *) videoURLWithData:(NSData *)data error:(NSError * __autoreleasing *)error
{
NSString *videoQuery = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSStringEncoding queryEncoding = NSUTF8StringEncoding;
NSDictionary *video = DictionaryWithQueryString(videoQuery, queryEncoding);
NSMutableArray *streamQueries = [[video[#"url_encoded_fmt_stream_map"] componentsSeparatedByString:#","] mutableCopy];
[streamQueries addObjectsFromArray:[video[#"adaptive_fmts"] componentsSeparatedByString:#","]];
NSMutableDictionary *streamURLs = [NSMutableDictionary new];
for (NSString *streamQuery in streamQueries)
{
NSDictionary *stream = DictionaryWithQueryString(streamQuery, queryEncoding);
NSString *type = stream[#"type"];
NSString *urlString = stream[#"url"];
if (urlString && [AVURLAsset isPlayableExtendedMIMEType:type])
{
NSURL *streamURL = [NSURL URLWithString:urlString];
NSString *signature = stream[#"sig"];
if (signature)
streamURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#&signature=%#", urlString, signature]];
if ([[DictionaryWithQueryString(streamURL.query, queryEncoding) allKeys] containsObject:#"signature"])
streamURLs[#([stream[#"itag"] integerValue])] = streamURL;
}
}
for (NSNumber *videoQuality in self.preferredVideoQualities)
{
NSURL *streamURL = streamURLs[videoQuality];
if (streamURL)
{
NSString *title = video[#"title"];
NSString *thumbnailSmall = video[#"thumbnail_url"];
NSString *thumbnailMedium = video[#"iurlsd"];
NSString *thumbnailLarge = video[#"iurlmaxres"];
NSMutableDictionary *userInfo = [NSMutableDictionary new];
if (title)
userInfo[XCDMetadataKeyTitle] = title;
if (thumbnailSmall)
userInfo[XCDMetadataKeySmallThumbnailURL] = [NSURL URLWithString:thumbnailSmall];
if (thumbnailMedium)
userInfo[XCDMetadataKeyMediumThumbnailURL] = [NSURL URLWithString:thumbnailMedium];
if (thumbnailLarge)
userInfo[XCDMetadataKeyLargeThumbnailURL] = [NSURL URLWithString:thumbnailLarge];
[[NSNotificationCenter defaultCenter] postNotificationName:XCDYouTubeVideoPlayerViewControllerDidReceiveMetadataNotification object:self userInfo:userInfo];
return streamURL;
}
}
if (error)
{
NSMutableDictionary *userInfo = [#{ NSURLErrorKey: self.connection.originalRequest.URL } mutableCopy];
NSString *reason = video[#"reason"];
if (reason)
{
reason = [reason stringByReplacingOccurrencesOfString:#"<br\\s*/?>" withString:#" " options:NSRegularExpressionSearch range:NSMakeRange(0, reason.length)];
NSRange range;
while ((range = [reason rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
reason = [reason stringByReplacingCharactersInRange:range withString:#""];
userInfo[NSLocalizedDescriptionKey] = reason;
}
NSInteger code = [video[#"errorcode"] integerValue];
*error = [NSError errorWithDomain:XCDYouTubeVideoErrorDomain code:code userInfo:userInfo];
}
return nil;
}
You should use the latest version (2.0.2 as of writing) of XCDYouTubeKit, the successor of XCDYouTubeVideoPlayerViewController. The video 5Uls9v1nnss should play fine.
I had a uipickerview in my detailed page. I want to get the value selected by default when I edit the respective record which comes from my tableviewcell. In short I had a tableview with 10 records. When I select a record from tableview cell it navigates to detailed page which contains three picker views with one component each. I want the picker view to load the selected value by default. Here is the below code how Iam loading the data. How can I display the selected value in -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row and one more thing is I am using UINavigationcontroller for this page? Guys Can u please help me out
-(void)loadprojects
{
NSString *post =[[NSString alloc] initWithFormat:#"username=%#",[self.projectpicker dataSource]];
//NSString *pickername = [self.projectpicker dataSource];
//NSString *key = #"Da9s^a2Rp4na6R$ikiAsav3Is#niWsa";
//NSString *encrypteduname = [AESCrypt encrypt:pickername password:key];
// Code for Project loading
NSString *projecturltemp = #"http://xxx.xxx/GetAssignedProjects";
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * projecturl =[NSString stringWithFormat:#"%#/%#",projecturltemp,usrid];
NSURL *url = [NSURL URLWithString:projecturl];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments error:&error];
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
if(!entries)
{
NSLog(#"Error : %#", error);
}
else{
for (NSDictionary *entry in entries) {
projID = [entries valueForKey:#"ID_PROJECT"];
projectNames = [entries valueForKey:#"NM_PROJECT"];
}
randomSelection=[BenefitNames arrayByAddingObjectsFromArray:projectNames];
randomSelectionID = [benID arrayByAddingObjectsFromArray:projID];
_projectpicker.delegate = self;
_projectpicker.dataSource = self;
}
} else {
}
}
-(void)loaddata
{
NSString *eventDate = self.projidstocancel;
[[NSUserDefaults standardUserDefaults] setObject:eventDate forKey:#"Eventdate"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSString *post =[[NSString alloc] initWithFormat:#"username : %#&Password :%#",[self.projectpicker dataSource],[self.projectpicker delegate]];
//NSString *pickername = [self.projectpicker dataSource];
//NSString *key = #"Da9s^a2Rp4na6R$ikiAsav3Is#niWsa";
//NSString *encrypteduname = [AESCrypt encrypt:pickername password:key];
// Code for Project loading
NSString *projecturltemp = #"http://xxx.xxxx/GetDetailsByID";
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * projecturl =[NSString stringWithFormat:#"%#/%#",projecturltemp,self.hdnRowcount];
NSURL *url = [NSURL URLWithString:projecturl];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments error:&error];
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
if(!entries)
{
NSLog(#"Error : %#", error);
}
else{
for (NSDictionary *entry in entries) {
projectNames = [entries valueForKey:#"NM_PROJECT"];
taskNames = [entries valueForKey:#"TASk_NAME"];
subtaskNames = [entries valueForKey:#"SUBTASK_NAME"];
hdnlblProjects.text = [[entries valueForKey:#"NM_PROJECT"]componentsJoinedByString:#""];
hdnlblTasks.text = [[entries valueForKey:#"TASk_NAME"]componentsJoinedByString:#""];
hdnlblSubTasks.text = [[entries valueForKey:#"SUBTASK_NAME"]componentsJoinedByString:#""];
txthours.text = [[entries valueForKey:#"No_Hours"]componentsJoinedByString:#""];
txtstatus.text = [[entries valueForKey:#"STATUS"]componentsJoinedByString:#""];
lblBenefitsLeaves.text = [[entries valueForKey:#"NM_LEAVE"]componentsJoinedByString:#""];
BenefitNames = [entries valueForKey:#"NM_LEAVE"];
projID = [entries valueForKey:#"ID_PROJECT"];
taskID = [entries valueForKey:#"ID_TASK"];
subtskID = [entries valueForKey:#"ID_SUB_TASK"];
}
lblProjects.text = [[projID valueForKey:#"description"] componentsJoinedByString:#""];
taskstring = [[taskID valueForKey:#"description"] componentsJoinedByString:#""];
subtaskstring = [[subtskID valueForKey:#"description"] componentsJoinedByString:#""];
bentest = [[BenefitNames valueForKey:#"description"] componentsJoinedByString:#""];
hrsdiff1 = [txthours.text floatValue];
}
} else {
}
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
int numberofRows = 0;
if([pickerView isEqual: _projectpicker]){
numberofRows = [randomSelection count];
return numberofRows;
}
else if([pickerView isEqual: _taskspicker]){
numberofRows = [taskNames count];
return numberofRows;
}
else if([pickerView isEqual: _subtaskspicker]){
numberofRows = [subtaskNames count];
return numberofRows;
}
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *title = #"Test";
if([pickerView isEqual: _projectpicker]){
title = [randomSelection objectAtIndex:row];
return title;
}
else if ([pickerView isEqual: _taskspicker]){
title = [taskNames objectAtIndex:row];
return title;
}
else if ([pickerView isEqual: _subtaskspicker]){
title = [subtaskNames objectAtIndex:row];
return title;
}
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//NSLog(#"%#",myArrayString);
//NSLog(#"%#",myTaskArrayString);
if([pickerView isEqual: _projectpicker]){
NSNumber *myProjectArrayString = [randomSelectionID objectAtIndex:row];
lblProjects.text = [NSString stringWithFormat:#"%#",myProjectArrayString];
lblProjects.hidden = YES;
lblBenefitsLeaves.text = [randomSelection objectAtIndex:row];
hdnlblProjects.text = [randomSelection objectAtIndex:row];
rownoedit = row;
lblTasks.text = #"0";
hdnlblTasks.text = #"--Select--";
lblSubTasks.text = #"0";
hdnlblSubTasks.text = #"--Select--";
[self loadtasks];
}
//lblProjects.hidden = YES;
else if([pickerView isEqual: _taskspicker])
{
NSNumber *myTaskArrayString = [taskID objectAtIndex:row];
lblTasks.text = [NSString stringWithFormat:#"%#",myTaskArrayString];
lblTasks.hidden = YES;
hdnlblTasks.text = [taskNames objectAtIndex:row];
lblSubTasks.text = #"0";
hdnlblSubTasks.text = #"--Select--";
[self loadsubtasks];
}
else if([pickerView isEqual: _subtaskspicker])
{
NSNumber *mysubtaskArrayString = [subtskID objectAtIndex:row];
lblSubTasks.text = [NSString stringWithFormat:#"%#",mysubtaskArrayString];
lblSubTasks.hidden = YES;
hdnlblSubTasks.text = [subtaskNames objectAtIndex:row];
//lblTasks.text = [taskNames objectAtIndex:[pickerView selectedRowInComponent:1]];
//lblTasks.text = [NSString stringWithFormat:#"%#", myTaskArrayString];
//lblSubTasks.text = [subtaskNames objectAtIndex:[pickerView selectedRowInComponent:2]];
}
}
First define a static variable and give it initial value you like to first on load
ex : static int selectedRow = 3
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:
(NSInteger)row inComponent:(NSInteger)component{
selectedRow = [pickerView selectedRowInComponent:0];
}
and then where you show pickerView place this line
[self selectRow:selectedRow inComponent:0 animated:YES];
Try with following code
[self.yourPickerViewName selectRow:self.valueName inComponent:0 animated:YES];
Where
self.valueName is value that select record from tableview cell. and Put above code after creation of your UIPickerView.
You can refer this to fetch selected value from pickerview
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if([pickerView isEqual:StatePicker])
{
stateName = [StateArray objectAtIndex:row]; //StateName is NSString, StateArray is Array
}
}