Affichage des articles dont le libellé est Active questions tagged ios - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged ios - Stack Overflow. Afficher tous les articles

lundi 29 juin 2015

Does appcelerator studio work without internet connection once its installed?


My system specifications are : 

 Operating System Name         = Mac OS X

      Version                     = 10.10

      Architecture                = 64bit

      # CPUs                      = 4

      Memory                      = 4294967296

    Node.js

      Node.js Version             = 0.12.4

      npm Version                 = 2.10.1

    Titanium CLI

      CLI Version                 = 4.0.1

    Titanium SDK

      SDK Version                 = 4.0.0.GA

      SDK Path                    = /Users/systemname/Library/Application Support/Titanium/mobilesdk/osx/4.0.0.GA

      Target Platform             = iphone

The problem that i am facing is that i need continous internet connection for launching the app on device.Is there some setting which i can make to run without internet connection?

Thanks in advance.


Check if value is in sqlite database before adding


I am trying to preload some values into a database from a .csv file, but if they already exist then skip them. I am able to successfully parse the csv file then have the following function to check if they exist in the database:

func GetPreloadedDriverExists(manufacturer: String, model: String, size: Float, impedance: Int) -> Bool
{
    //1
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!

    //2
    let fetchRequest = NSFetchRequest(entityName:"Drivers")
    fetchRequest.propertiesToFetch = ["size"]
    fetchRequest.returnsObjectsAsFaults = false
    fetchRequest.predicate = NSPredicate(format: "(manufacturer MATCHES %@) AND (model MATCHES %@) AND (#size == %@) AND (impedance == %@) AND (isRemovable == FALSE)", "\(manufacturer)", "\(model)", "\(size)", "\(impedance)")

    //3
    var error: NSError?

    let fetchedResults:NSArray = (managedContext.executeFetchRequest(fetchRequest, error: &error))!

    return fetchedResults.count == 0 ? false : true
}

The first time through this return false as I would expect for all entries, but when I open the sqlite file on the device, it is blank. If I remove the condition to check if they already exist, the database populates correctly.

Here is the loop I am using to add the entries into the database.

if let managedObjectContext = self.managedObjectContext {
     for item in items {
     // Check if driver already exists in database, if not add it.
          if(!GetPreloadedDriverExists(item.manufacturer, model: item.model, size: (item.size as NSString).floatValue, impedance: (item.impedance as NSString).integerValue))
          {
               println("Value does not exist")
               let menuItem = NSEntityDescription.insertNewObjectForEntityForName("Drivers", inManagedObjectContext: managedObjectContext) as! Drivers
                        menuItem.manufacturer = item.manufacturer
                        menuItem.model = item.model
                        menuItem.size = (item.size as NSString).floatValue
                        menuItem.impedance = (item.impedance as NSString).integerValue

                if managedObjectContext.save(&error) != true {
                     println("insert error: \(error!.localizedDescription)")
                }
           }
      }
 }

Thank you for the help and any feedback.


Making a web proxy for ipads by using a iframe


To keep this short, I'd like to make a website that, using a iframe connects to my server and from their to any website the user wants this would allow ipads to connect to my site and through a proxy to access google, facebook, ect. Let me know if any more explanation is necessary P.S. - I cant use the built in vpn on ipads due to restrictions.


Unknown attribute 'objc_boxable' ignored?


I'm trying to typedef a struct and box it into a dictionary value. I tried this code from the clang website, but no dice:

typedef struct __attribute__((objc_boxable)) _SizeA {
    CGFloat height;
    CGFloat width;
} SizeA;

The typedef is warned `Unknown attribute 'objc_boxable' ignored.

Xcode 6.3 with iOS SDK 8.3 targeting 8.0. Is there a trick here I'm missing?


iOS: User inactivity/idle


I want to find the user in activity and do some operation if the user inactive for some times. I have used the below link to implement the inactivity: stack overflow question But issue is that the TIMERUIApplication is not invoked all times. When I killed the app and reopen it the TIMERUIApplication is not called and the notification is not fired. Does anyone have any idea about this. Thanks in advance.


Share Facebook permissions between Android and iOS


I'm developing an App for Android and iOS. One of the permissions I ask from Facebook is for the user friends, but since you can only get the friends that also gave permissions to your App and since I had to register an App of iOS and one of Android in Facebook from iOS I can only get the users that are using my App on iOS.

How can I get all the friends that gave permission of my App regardless of the platform?


UIAlertView for when fetching JSON fails


I'm trying to get this UIAlertView to run when fetching the JSON data fails, but i can't seem to get it to work. I'd appreciate it if someone could show me how to do it or point me in the right direction!


Email PDF file on iOS


I'm writing a function to send a pdf file via email. On iOS I am encountering an issue where a pdf file gets generated and attached to an email and sent successfully, but the received email does not contain the original pdf file for some reason.

Here is my implementation using MFMailComposeViewController.

MFMailComposeViewController *mailer = [[[MFMailComposeViewController alloc] init] autorelease];
[mailer setMailComposeDelegate: id(m_delegate)];
[mailer setSubject:subject.toNSString()];
NSMutableArray *toRecipients = [[NSMutableArray alloc] init];
for(int i = 0; i < recipients.length(); i++)
{
    [toRecipients addObject:recipients.at(i).toNSString()];
}
[mailer setToRecipients:toRecipients];
NSString *emailBody = body.toNSString();
[mailer setMessageBody:emailBody isHTML:NO];


// Determine the file name and extension
attachedFile = "/var/mobile/Containers/Data/Application/1DFBF012-4838-4350-B465-ECF247831EB3/Library/Application Support/test.pdf";
NSArray *filepart = [attachedFile.toNSString() componentsSeparatedByString:@"."];
NSString *filename = [filepart objectAtIndex:0];
NSString *extension = [filepart objectAtIndex:1];

// Get the resource path and read the file using NSData
NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];

// Determine the MIME type
NSString *mimeType;
if ([extension isEqualToString:@"jpg"]) {
    mimeType = @"image/jpeg";
} else if ([extension isEqualToString:@"png"]) {
    mimeType = @"image/png";
} else if ([extension isEqualToString:@"doc"]) {
    mimeType = @"application/msword";
} else if ([extension isEqualToString:@"ppt"]) {
    mimeType = @"application/vnd.ms-powerpoint";
} else if ([extension isEqualToString:@"html"]) {
    mimeType = @"text/html";
} else if ([extension isEqualToString:@"pdf"]) {
    mimeType = @"application/pdf";
}

// Add attachment
[mailer addAttachmentData:fileData mimeType:mimeType fileName:filename];


[qtController presentViewController:mailer animated:YES completion:nil];

I was able to see the file got attached to an email and sent it. I was able to receive the email sent. However, when I opened up the email it did not contain the file attached.

Any suggestion how I can troubleshoot this issue?

Here is my implementation of saving PDF file which follows standard file system path for saving application data.

/* Generate PDF file for sharing */
CGRect pageRect = CGRectMake(0, 0, 640, 480);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString * newFilePath = [documentPath stringByAppendingPathComponent:@"test.pdf"];
NSString *strFilename = newFilePath;
MyCreatePDFFile(pageRect, [strFilename UTF8String]);

I'm looking if there is a way to get the PDF file generated for trouble-shooting. It's located in Application Support directory which other application has no access to due to sand box policy. How do I get to access the PDF file?


Notification Issues in Xcode 6.3.2 With Swift


I'm using Swift in Xcode 6.3.2, and I'm trying to develop an app that sends local notifications. How do I get user permission to display notifications?


Programaticaly Click 10 UIButtons one after another in UIScrollView


I am developing one control where 10 UIButtons are added in UIScrollView. Now i have a requirement to click every Button one after another after some delay. can you all guide me how to do that?

here is the code what i have done.

in viewcontroller.h file

@property (weak) IBOutlet UIScrollView *mapScrollView;
@property (strong) UIButton *addContactIcon;

in viewcontroller.m file

// Set up ScrollView with UIButtons
NSUInteger xPosition = 1;
NSUInteger countIndex = 0;
for (ContactModule *sortedContacts in _distanceList) {

    _addContactIcon = [[UIButton alloc] initWithFrame:CGRectMake(xPosition, 7, 30, 30)];
    _addContactIcon.tag = countIndex;
    [_addContactIcon addTarget:self action:@selector(mapsScrollButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    _addContactIcon.layer.cornerRadius = 2.0;
    _addContactIcon.clipsToBounds = YES;
    [_addContactIcon setBackgroundImage:[UIImage imageWithContentsOfFile:dataPath] forState:UIControlStateNormal];
    [_addContactIcon setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_mapScrollView addSubview:_addContactIcon];
    xPosition += _addContactIcon.frame.size.width + 2;
    countIndex = countIndex + 1;
}
_mapScrollView.contentSize = CGSizeMake(30 * _distanceList.count + 34, 40);
[_mapScrollView setShowsHorizontalScrollIndicator:NO];

Here is the Button Click Method For Every Button:

- (void)mapsScrollButtonClicked:(UIButton *)clickButton {

    // Set Annotation Callout
    [_mapsView selectAnnotation:[_mapsView.annotations objectAtIndex:clickButton.tag] animated:YES];
}

Now the requirement is I want to call Action Method for Every UIButtons in UIScrollview. for that i am doing something wrong below. help me with that:

for(NSUInteger count=0; count<[_distanceList count];count++)    {

            [UIView animateWithDuration:0.4
                              delay:0.8
                            options:0
                         animations:^{
                             [_addContactIcon sendActionsForControlEvents:UIControlEventTouchUpInside];
                         } completion:nil];
 }


how to give Page View Controller a "Cover Vertical" transition style


With a Navigation View Controller, I can give a "Cover Vertical" transition style animation. However, having trouble replicating that with a Page View Controller. The only options given in the story board are "Scroll" and "Page Curl". Is there a way to do this programmatically?


UIPanGestureRecognizer at view with UIScrollView


I have a view with UIPanGestureRecognizer.

UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc]
                                          initWithTarget:self action:@selector(handlePan:)];
    [recognizer setMaximumNumberOfTouches:1];
    [recognizer setDelegate:self];

[self.view addGestureRecognizer: recognizer];

=======
-(void) handlePan:(UIPanGestureRecognizer*)gestureRecognizer
{
  move subview of self.view
}

subview have a scroll view inside. how to capture gesture with event -handlePan: when scroll view is at the end of horizontal scrolling?

enter image description here


Office 365 iOS SDK - How to invoke SharePoint REST API


All the iOS SDK samples provide working code for accessing Mail, Calendar, ODfB FIles, but none show how to access SharePoint list items. So I am trying a simple REST call in Swift, but keep getting the following error:

[0] (null) @"error_description" : @"Unsupported security token.

Here is a subset of my code when my App starts:

var resourceID : String = "http://ift.tt/1qL2pxV"
var authorityURL : String = "http://ift.tt/1t9uKz6"
var clientID : String = "xxd4200eb-7284-41be-a434-abb269b82f0f"
var redirectURI : NSURL = NSURL(string: "http://ift.tt/1RyDJ4q")!

override func viewDidLoad() {
    super.viewDidLoad()

    var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

    var er : ADAuthenticationError? = nil
    var authContext:ADAuthenticationContext = ADAuthenticationContext(authority: authorityURL, error: &er)

    authContext.acquireTokenWithResource(resourceID, clientId: clientID, redirectUri: redirectURI) { (result: ADAuthenticationResult!) -> Void in
        if (result.accessToken == nil) {
            println("token nil")
        } else {
            defaults.setObject(result.accessToken, forKey: "accessTokenDefault")
            defaults.synchronize()
            println("accessToken: \(result.accessToken)")
        }
    }
}

Then, once I get the Token, I invoke the following code that tries an http GET but fails:

    var resolver : MSODataDefaultDependencyResolver = MSODataDefaultDependencyResolver()

    var credentials : MSODataOAuthCredentials = MSODataOAuthCredentials()
    var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

    credentials.addToken(defaults.objectForKey("accessTokenDefault") as! String)
    var credentialsImpl : MSODataCredentialsImpl = MSODataCredentialsImpl()
    credentialsImpl.setCredentials(credentials)
    resolver.setCredentialsFactory(credentialsImpl)

    //build API string to get a sample list info
    let request = NSMutableURLRequest(URL: NSURL(string: "http://ift.tt/1HfT3Dn")!)
    request.HTTPMethod = "GET"
    let token = defaults.stringForKey("accessTokenDefault")
    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    request.setValue("application/json; odata=verbose", forHTTPHeaderField: "accept")

    //make the call to the SharePoint REST API
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var error:NSError? = nil
        let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary

        if (jsonResult != nil) {
            //parse the json into File objects in the table view
            let results:NSArray = (jsonResult["d"] as! NSDictionary)["results"] as! NSArray

And this is where it fails with the error message. Monitoring the web traffic, the following is a bit more details about what is going on:

This is my request (RAW):

GET /_api/web?$select=Title HTTP/1.1
Host: mytenant.sharepoint.com
Connection: keep-alive
Proxy-Connection: keep-alive
Accept: application/json; odata=verbose
User-Agent: O365Demo/1 CFNetwork/711.3.18 Darwin/14.3.0
Accept-Language: en-us
Authorization: Bearer Optional("eyJ0eXAiOiJKV1QiLDJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJodHRwczovL3VtYWtub3cuc2hhcmVwb2ludC5jb20iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC81NmZjOTc3OC04YWFjLTQ1ZDItOTMwNS1iOTE3MWZmYWZhOGMvIiwiaWF0IjoxNDM1MjI3Nzk1LCJuYmYiOjE0MzUyMjc3OTUsImV4cCI6MTQzNTIzMTY5NSwidmVyIjoiMS4wIiwidGlkIjoiNTZmYzk3NzgtOGFhYy00NWQyLTkzMDUtYjkxNzFmZmFmYThjIiwib2lkIjoiOGUyZTBlZDQtYmEzNC00YWM4LTkwYmMtNWQ3NGQ3MzE4YjkyIiwidXBuIjoicGllcnJlQHVtYWtub3cuY29tIiwicHVpZCI6IjEwMDMwMDAwODUyMUY3NjYiLCJzdWIiOiJqR3BHQ1VDdDNYTnM2b0pjSkgxVldQOUwyV1JLa3lIOHhxWHlKbVFaSV8wIiwiZ2l2ZW5fbmFtZSI6IlBpZXJyZSIsImZhbWlseV9uYW1lIjoiQm91cmFzc2EiLCJuYW1lIjoiUGllcnJlIEJvdXJhc3NhIiwiYW1yIjpbInB3ZCJdLCJ1bmlxdWVfbmFtZSI6InBpZXJyZUB1bWFrbm93LmNvbSIsImFwcGlkIjoiNmQ0MjAwZWItNzI4NC00MWJlLWE0MzQtYWJiMjY5YjgyZjBmIiwiYXBwaWRhY3IiOiIwIiwic2NwIjoiQWxsU2l0ZXMuTWFuYWdlIEFsbFNpdGVzLlJlYWQgQ2FsZW5kYXJzLlJlYWRXcml0ZSBGaWxlcy5SZWFkIEdyb3VwLlJlYWQuQWxsIEdyb3VwLlJlYWRXcml0ZS5BbGwgTXlGaWxlcy5SZWFkIE15RmlsZXMuV3JpdGUgU2l0ZXMuUmVhZC5BbGwgU2l0ZXMuU2VhcmNoLkFsbCBUZXJtU3RvcmUuUmVhZC5BbGwgVXNlci5SZWFkIFVzZXIuUmVhZFdyaXRlIFVzZXIuUmVhZFdyaXRlLkFsbCIsImFjciI6IjEifQ.aAkaEIFuOeiI0ZRydzaOBTl5wyqLDYBHfvbSj6nZAk4jQKBZF6BhJsAAnhu9qj8oMR2gUdVr3vCNgzefvlZxcf3u0k6R8g4176M-bU3rAABri9DjyaZJ24jMs1u-kL0h5Ee8mvNXSI7BF7Qv9JoeHIiXLei_SXba1s8mhdwMaw9Se9tl8MbBFPLDDBLXUa4YgC_rYWO7G7rw3JEe3GmEV9NffZ7zklXxd55P8fxtbz0-KhI0wbRHIXN69wAuC0jiqhJ4FCCGzLvTuuUbirhURrhi4UizYpLWqqnr0I8zWAMvr8WUXCWtZhPkzOZ5teqbvBwp1UwYui42O6S0PfYKzQ")
Accept-Encoding: gzip, deflate

And finally the RAW response from the site

HTTP/1.1 401 Unauthorized
Server: Microsoft-IIS/8.5
x-ms-diagnostics: 3000006;reason="Token contains invalid signature.";category="invalid_client"
SPRequestGuid: 84c9139d-807c-2000-0e59-4caf75bd097f
request-id: 84c9139d-807c-2000-0e59-4caf75bd097f
SPRequestDuration: 19
SPIisLatency: 1
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 16.0.0.4107
X-Content-Type-Options: nosniff
X-MS-InvokeApp: 1; RequireReadOnly
P3P: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
WWW-Authenticate: Bearer realm="56fc9778-8aac-45d2-9305-b9171ffafa8c",client_id="00000003-0000-0ff1-ce00-000000000000",trusted_issuers="00000001-0000-0000-c000-000000000000@*,http://ift.tt/1RyDJ4r",authorization_uri="http://ift.tt/1nLu7IU"
Date: Thu, 25 Jun 2015 11:12:40 GMT
Content-Length: 51

{"error_description":"Unsupported security token."}

So there is something obviously wrong with the way I use the Token provided, but with my very limited OAuth2 knowledge and the lack of samples, I am at a lost.

Any help is greatly appreciated!


Using Intents in PhoneGap/Cordova to call default maps app on ios and android platform


I need some help implementing intents in PhoneGap/Cordova for a program that I have running on android and on ios. It's a driver application but I want to link it to the phones default maps app so that it can gps to it once the driver selects a destination. Something Uber like.


Detect when second tableview cell comes into view - then perform an action


I've got a UITableView in a UIViewController, as well as a filter button. I hide the filter button when the user starts to scroll down the list. I want to then show the filter button when the second cell (index 1) is visible. However, I can't get this desired effect, I can only get it to appear when it reaches the top. Here is my code for when it reaches the top (I then show the filter button again).

//determines when the tableview was scrolled
-(void) scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint currentOffset = scrollView.contentOffset;
     //tableview is scrolled down
    if (currentOffset.y > self.lastContentOffset.y)
      {

    //if the showFilter button is visible i.e alpha is greater than 0
        if (self.showFilter.alpha==1.0) {

            [UIView animateWithDuration:1 animations:^{

                //hide show filter button
                self.showFilter.alpha=0.0;
                //I also adjust the frames of a tableview here
            }];

        }


    }


    //determines if it is scrolled back to the top
    if (self.showFilter.alpha==0.0 && currentOffset.y==0) {
        [UIView animateWithDuration:0.3 animations:^{
            //show filter button
            self.showFilter.alpha=1.0;

          //i also adjust the frames of the tableview here
        }];
    }

    self.lastContentOffset = currentOffset;
}

I have also tried:

if (self.showFilter.alpha==0.0 && currentOffset.y<160)

But it doesn't work to the desired effect as the tableview jumps off the screen. Is there another way to get this desired effect?


Fetching JSON data after failed retrieval


In my application, I am fetching JSON data. Occasionally, the application will fail to fetch it and when I print the responseObject, it returns ( ). I would like to make an if statement so that when this happens, a UIAlertView will show up. Right now, I have an if statement saying that if self.jobs == nil, the alert will come up, but that is not working. I'd really appreciate any help!

- (void)viewDidLoad
{

[super viewDidLoad];

//Fetch JSON
NSString *urlAsString = [NSString stringWithFormat:@"http://ift.tt/1MXKCe4", LANGUAGE, TOWN];
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];

//Parse JSON
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
self.jobs  = (NSArray *)responseObject;

if(self.jobs != nil)
{
    [self.tableView reloadData];
}
else
{
    UIAlertView* alert_view = [[UIAlertView alloc]
                               initWithTitle: @"Failed to retrieve data" message: nil delegate: self
                               cancelButtonTitle: @"cancel" otherButtonTitles: @"Retry", nil];
    [alert_view show];
}
}

//Upon failure
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
 UIAlertView *aV = [[UIAlertView alloc]
                           initWithTitle:@"Error" message:[error localizedDescription] delegate: nil
                                           cancelButtonTitle:@"Ok" otherButtonTitles:nil];
 [aV show];
 }];


Unexpectedly found nil while unwrapping an Optional value while opening UIViewController


I'm doing a simple tableview app with swift, in which you open a new view controller programatically after clicking on a table row:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

//GLobals
@IBOutlet weak var table: UITableView!
//Table View Data

let cats :[String] = ["Gala","Vito","Odin","Ema"]

override func viewDidLoad() {
    super.viewDidLoad()

    table.delegate = self
    table.dataSource = self
}

// MARK:  UITextFieldDelegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cats.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = table.dequeueReusableCellWithIdentifier("CustomTextCell", forIndexPath: indexPath) as! UITableViewCell

    let row = indexPath.row
    cell.textLabel?.text = cats[row]

    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    let row = indexPath.row
    let cat : String = cats[row];
    println(cat)

    //Save cat for detail view
    var defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(cat, forKey: "cat")
    defaults.synchronize()


    let detail:Detail = Detail();
    self.presentViewController(detail, animated: true, completion: nil);
}
}

The code in the detail view is the following:

class Detail: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.whiteColor()

    let defeaults = NSUserDefaults.standardUserDefaults()

    let cat = defeaults.stringForKey("cat")

    var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
    label.center = CGPointMake(160, 284)
    label.textAlignment = NSTextAlignment.Center
    label.text = cat

    self.view.addSubview(label)
}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    let home:ViewController = ViewController()
    self.presentViewController(home, animated: true, completion: nil)
}

However when the app goes back to ViewController I'm having "unexpectedly found nil while unwrapping an Optional value "

the error

I have try some of the other answers to this problem including, warping with if == nil some of the values, but I still can't find what is the problem.

I'm assuming the UIViewController is not loading the UITableViewDelegate and UITableViewDataSource again, but I don't understand why... and how would you load them from another view anyway?


Trouble understanding resuming cells in collection views


I'm following a site to help learn swift and I'm getting confused about this part right here. Basically we added the if cell.imageview.image == nil statement so hat when the collection view loads and you scroll the image doesn't reload the filters. What I don't understand is if you scroll down a cell is reused for the bottom row, now why if I scroll back up doesn't it have to reload the filter? is that data saved somewhere so when I scroll up the properties don't have to repopulate? and If thats the case why would I have to use that if statement at all?

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as! FilterCell

    if cell.imageView.image == nil {
    cell.imageView.image = placeholder

    let filterQueue: dispatch_queue_t = dispatch_queue_create("filter queue", nil)

    dispatch_async(filterQueue, { () -> Void in
        let filterImage = self.filteredImageFromImage(self.thisFeeditem.thumbNail, filter: self.filters[indexPath.row])

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            cell.imageView.image = filterImage
            })
        })
    }
    return cell
}


Make NSOperationQueue synchronous


How can I make NSOperationQueue synchronous? I did tried this by subclassing NSOperation and setting "setMaxConcurrentOperationCount" to 1. And also adding dependencies on previous operations using "addDependency" method.

Adding Code:

if(!operationQueue)
{
    operationQueue = [[MyQueue alloc] init];
}
[operationQueue setMaxConcurrentOperationCount:1];
UploadFileOperation *uploadFileOperation = [[UploadFileOperation alloc] initWithObject:someObject];
[operationQueue addOperation:uploadFileOperation];

Now when log the upload progress for two files it shows that both the files are uploading at the same time. Like this: File1 - 17.647026% Uploaded File1 - 18.352907% Uploaded File2 - 0.870381% Uploaded File2 - 1.740762% Uploaded File2 - 2.611142% Uploaded File2 - 3.481523% Uploaded File1 - 19.058788% Uploaded


Complex fetch-request for NSFetchedResultsController


Here's a simplified look for my model:

  • Media has property 'status' that can be either 'Uploading' or 'Uploaded'.
  • User has property 'syncStatus' that be either 'NotSynced' or 'Synced'.
  • ObjectX is a 'linking' object between User and Media
  • User has to-many relationship to ObjectX
  • ObjectX has to-one relationship to Media

Is there any way to use NSFetchedResultsController to fetch all Users that are 'Synced' and whose all media are 'Uploaded'? It would have to update its content also when 'Media' status is changed so that new User should be fetched. I've heard NSFetchedResultsController doesn't work well with such complex fetch requests.

Model Graph