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

mercredi 5 août 2015

Errors in retrieving all Parse data from a class


I am retrieving multiple items from Parse and would like to loop through them and add them to an array. Below is my code. I have several errors:

  Cannot invoke append with an argument list of type '(String)'
  Argument for generic parameter 'T' could not be inferred

//end errors

var query = PFQuery(className:"myClass")
    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]?, error: NSError?) -> Void in

    if error == nil {
    // The find succeeded.
    // Do something with the found objects
    if let objects = objects as? [PFObject] {

                for object in objects {


if let stringObject = object["values"] as? String {
                            self.myArray.append(stringObject)
                        }
                    }

                    }


        } else {

            println("Error: \(error!) \(error!.userInfo!)")
        }
    }

I'd be grateful for any help.

Here is where I create the array:

var myArray: Array = [String]()



via Chebli Mohamed

Store paragraphs of text (including line breaks) in cloud kit and query


I have another newbie question. Hopefully one of you programming gurus can help me with it.

I'm trying to fetch multiple paragraphs of text (e.g. a news article) from CloudKit. I don't know how to format the text so that it includes a line break. I've been told that I should use CKAsset instead of a String on the CloudKit record, but I don't understand how it's supposed to be formatted.

Can anyone help me understand this more?

Thanks in advance.



via Chebli Mohamed

Swift - UIAlertView - Bold text in message


I want to highlight some words in my UIAlertView message, either by making it bold, or, by underline.

let message = "This is normal text.\nBold Title:\n This is normal text"

let alert = UIAlertView(title: "Title", message: message, delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")

alert.show()

How could I make "Bold Title" bold (or underline) in message?



via Chebli Mohamed

IOS / Swift2 - List all files in directory


I have a server running nginx. I have a directory in my server where I have several audio files. I replaced my real url by "url".

How can I list them. I want to make a table with all of the files in that directory.

When I print weContent I get:

403 Forbidden

override func viewDidLoad() {
    super.viewDidLoad()

    let url = NSURL(string: "url")!

    //self.webView.loadRequest(NSURLRequest(URL: url))

    let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in

        // Will happen when task completes

        if let urlContent = data {

            let webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)

            print(webContent)

            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                self.webView.loadHTMLString(String(webContent!), baseURL: nil)

            })

        } else {

            // Show error message

        }

    }

    task.resume()

}

Thank you



via Chebli Mohamed

Why: "Attempting to load .. while deallocating... :UISearchController:"


I have storyboard (ViewControllerA) that has a button that pushes ViewControllerB. VCB is

ViewControllerB has a "back" method as follows: (I've tried this both v1 and v2)

v1:

- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
completion:nil];
}

v2:
- (IBAction)back:(id)sender {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

Both methods give the following warning -- as well as some unexpected behavior.

The warning is:

Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior ()

I used Apple's sample (membership required) to add the new UISearchController.

I tried using the back methods in the base controller, the main controller and the search controller. All give me the same result.

Has anyone come across this? How do I resolve it?



via Chebli Mohamed

apple llvm 6.1 error invalid library name -stdlib=libc++ compiler-default


When I reference C++ codes in an O-C file, I modify the .m file to .mm according to articles on the internet. Then I build the project. Unfortunately, I got the error msg below:

apple llvm 6.1 error invalid library name -stdlib=libc++ compiler-default

I have tried all the compilers in Building Settings->C++ Language but they don't work. I have tried multiple syntaxes but they didn't work.

Why is this happening and how can I solve it?



via Chebli Mohamed

How can i check image contain data or not in this Response


This is my response API. The image data dynamically changes,with more image at a time or else no image at a time. I have check as ([image_array count]==0) but app crash due to empty array.
Error

reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(
    0   CoreFoundation                      0x0243edf6 __exceptionPreprocess + 182

API RESPONSE


{
    response =     {
        Details =         {
            ID = 4;
            address = "";
            ancestors =             (
            );
            "comment_count" = 0;
            "comment_status" = closed;
            description = "";
            "description_pt" = "";
            duration = 2;
            "event_address" = "";
            "event_location" = ",";
            "event_location_option" = "";
            "event_place_address" = "";
            "event_place_email" = "";
            "event_place_location" = "";
            "event_place_phone" = "";
            "event_place_website" = "";
            filter = raw;
            guid = "";
            images =             (
            );
            "like_count" = 0;
            "like_status" = FALSE;
            location = "";
            "menu_order" = 0;
            "ping_status" = closed;
            pinged = "";
            "place_event_count" = "";
            "place_event_id" = "";
            "place_id" = "";
            "post_author" = 5;
            "post_category" =             (
            );
            "post_content" = "";
            "post_content_filtered" = "";
            "post_date" = "2015-07-31 ";
            "post_date_gmt" = "2015-07-31 ";
            "post_excerpt" = "";
            "post_mime_type" = "";
            "post_modified" = "2015-07-31 ";
            "post_modified_gmt" = "2015-07-31 ";
            "post_name" = 48;
            "post_parent" = 0;
            "post_password" = "";
            "post_status" = publish;
            "post_title" = "";
            "post_type" = events;
            "tags_input" =             (
            );
            time = "17:50:30";
            title = "";
            "title_pt" = "";
            "to_ping" = "";
            video = "";
            website = "";
        };
        Message = "Post Details";
        httpCode = 10;
    };
}



via Chebli Mohamed

How to connect to Virtual MIDI host on iOS


I am developing a MIDI controller iOS app. So far I have managed to connect it to GarageBand on my Mac over wifi using NSNetServiceBrowser to find service with type "_apple-midi._udp" and then creating MIDI connection for the found service.

Now I want to integrate my app with Virtual MIDI host app like SampleTank. Googling for a few days, I can't find any examples of how to achive this. I need to get the list of all available MIDI hosts on the device and connect to one.

Could you please give me a direction where to find required info to accomplish my task?



via Chebli Mohamed

CMSampleBufferRef to aac ADTs and RTP payload


Need help on below queries..

I m trying to build an RTSP based application for mac. I am capturing audio through the mac inbuilt mic using AVCaptureSession class.

I am using following code to set the delegate of the audiooutput

AVCaptureAudioDataOutput *audioOut = [[AVCaptureAudioDataOutput alloc] init];

dispatch_queue_t audioCaptureQueue = dispatch_queue_create("Audio Capture Queue", DISPATCH_QUEUE_SERIAL);
[audioOut setSampleBufferDelegate:self queue:audioCaptureQueue];
if ([self.captureWebCamSession canAddOutput:audioOut])
    [self.captureWebCamSession addOutput:audioOut];

AudioChannelLayout channelLayout;
memset(&channelLayout, 0, sizeof(AudioChannelLayout));
channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;

NSDictionary *outputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                [ NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
                                [ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey,
                                [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
                                [NSData dataWithBytes:&channelLayout length:sizeof(AudioChannelLayout)], AVChannelLayoutKey,
                                [ NSNumber numberWithInt: 128000 ], AVEncoderBitRateKey,nil];

audioOut.audioSettings = outputSettings;

Now I am getting aac encoded buffer in the

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection

Now can someone tell me how can i get the aac adts data from the sample buffer and than convert it into the RTP payload which can be transferred to rtsp server for broadcasting.

Thanks in advance for any help..



via Chebli Mohamed

Keyboard Extension doesn't install the main app


I have created new schemes for both main app and extension.
When I run the main app on device, it works as expected. But when I run the keyboard extension it runs but it is not under debug, and if I remove the app previously then it wouldn't be installed. Can anybody explain what's happened?



via Chebli Mohamed

UIPickerView showing empty grey box Swift


I haven't a whole lot of code, so I might as well copy it here.

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{

    var buildings = ["BankBuilding", "Cinema" , "CornerShop", "Greg's House"]

    @IBOutlet weak var buildText: UITextField!

    var buildPickers:UIPickerView = UIPickerView()

    override func viewDidLoad() {
        super.viewDidLoad()

        buildPickers = UIPickerView()
        buildPickers.delegate = self
        buildPickers.hidden = true;
        buildText.inputView = buildPickers
        buildText.text = buildings[0]        
    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        println("Count: \(buildings.count)")
        return buildings.count
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        println("creating title: \(buildings[row])")
        return buildings[row]
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        println("Selected: \(buildings[row])")
        buildText.text = buildings[row]
        buildPickers.hidden = true;
    }

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        buildPickers.hidden = false
        return false
    }
}

The print statements are correct. For numberOfRows... and titleForRow it is printing the correct Strings.

But there is no prints for didSelectRow because, well, I can't select a row.

This is what I get:

enter image description here

You can ignore the Google Map in the background, that shouldn't interfere with the Picker View and is just set up in the StoryBoard.

The Grey window appears when I click on the textField but never shows any content. But the print statements say otherwise.

Does anyone know why this is the case?



via Chebli Mohamed

NSOperationQueue with operation block not working as desired in SWIFT


I have to check series of operations sequentially. but in case of any operation failed i need to call other operation before executing listed operation in queue.

for example:

priority 1 : Fetch all companies lookups
priority 2 : Fetch all regions
priority 3...N : Fetch all cities individually for each region

in each operation i pass one key which valid only for 2 hours... suppose key was generated on 10am and i will start fetching data from server and it will take 15 mins to fetch all data completely.

but the problem is i have started fetching data on 11:59 am and during fetching information key expired. so i need to send one more request to get key and proceed further for next operations.

so it looks like:
priority 1 : Fetch all companies lookups with key
priority 2 : Fetch all regions (i.e. 4 Regions available) with key
   priority 3 : Fetch all cities for region 1 with key
   priority 4 : Fetch all cities for region 2 with key (here key is expire) so for taking new key need to add new operation here, which fetch new key which is valid again for next two hours.
   priority 5 : Fetch all cities for region 3 with new key
   priority 6 : Fetch all cities for region 4 with new key

Code which i have tried:

var queue = NSOperationQueue.mainQueue()
queue.addOperationWithBlock({
  callService(“http://dsn/FetchingCompanyData”)
}

queue.addOperationWithBlock({
  callService(“http://dsn/FetchingRegionData”)
  //get region List here
  for region in regions{
   queue.addOperationWithBlock({
    callService(“http://dsn/FetchingCities?region=\(region.code)”)
    //check in response if response return message like KEY_EXPIRE
    if(error){
      queue.addOperationWithBlock({
        var newKey = callService(“http://dsn/FetchingCities?region=\(region.code)”)
        setKeyToCache(newKey)
      })
    }
  }
}
}

fun callService(urlStr: String){
    let myURL = NSURL(string: urlStr)!
    var key = getKeyFromCache()
    var request = NSMutableURLRequest(URL: myURL)
    var errorHandling = ErrorHandling()
    request.HTTPMethod = "POST"
    request.timeoutInterval = 10000.0
    request.addValue("application/xml", forHTTPHeaderField: "Content-Type")
    request.addValue("application/xml", forHTTPHeaderField: "Accept")
    request.setValue("Basic \(key)", forHTTPHeaderField: "Authorization")

    NSURLConnection.sendAsynchronousRequest(request, queue: queue) { response, data, error in ..}
}

this code is not working as desire.

it adding operations in queue as below:

Queue:
Operation 1: Fetch companies
Operation 2: Fetch Regions
Operation 3: Fetch cities for region 1
Operation 4: Fetch cities for region 2
Operation 5: Fetch cities for region 3
Operation 6: Fetch cities for region 4
Operation 7: Fetch new key for region 1
Operation 7: Fetch new key for region 2
Operation 7: Fetch new key for region 3
Operation 7: Fetch new key for region 4

instead of this i want sequence of operations as below.

 Operation 1: Fetch companies
    Operation 2: Fetch Regions
    Operation 3: Fetch cities for region 1
    Operation 4: Fetch cities for region 2
    Operation 5: Fetch new key for region 2
    Operation 6: Again Fetch cities for region 2
    Operation 7: Fetch cities for region 3
    Operation 8: Fetch cities for region 4

Any help will be more appreciated.



via Chebli Mohamed

hmac nsdictionary - express req.body


i am trying to do a generic - hmac verification with an iOS app and an express node.js app.

generating the hmac using given samples at: http://ift.tt/1P42qG1

having the following problem: subclassed AFHTTPRequestOperationManager to gain access to POST: i want to hmac the nsdictionary parameters.

so convert the nsdicionary to json - hmac it - and set hmac header in request. on the receiver side, i use crypto-js and express to access the req.body - and hmac the json object.

problem is! - thos keys are not in same oder, even if i force the sort on the keys in nsdictionary, the transoformed json does not come in the order way.

after hours of googling i accepted that json objects cannot be orderd, in an reliable way.

so what is the best-practice to hmac an nsdictionary, by ignoring the order? (i could hmac on only a few keys, but that would be way to less generic, mean adding a dictionary key would require code change in ios and express)

generating the hmac only based on the URI - works fine, but its a way to open :)

UPDATE: to be a bit more specific.

on the app i transform my nsdictionary to json by and then calculate the hmac of the json_string

NSDicationary * dic = @{@"key1", "value1",@"key2", "value2"} 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
                                                       options:(NSJSONWritingOptions)    (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                         error:&error];

NSString * json_str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]

and i do a AFNetworking POST request calling passing my nsdictionary as parameters:

- (AFHTTPRequestOperation *)POST:NSString *)URLString parameters:(id)parameters   success:(void (^)(AFHTTPRequestOperation *operation,id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

on the receiver app (node.js/express) i get the ctx.req.body containing the javascript object from the POST request -> but here it does not have the same order as in the json encoded string from the app (and i have not found a way to preserve order)

as i am not knowing what keys are in nsdicationary a static key-hmac would not work.

regards helmut



via Chebli Mohamed

iCarousel inside Tableview


I am trying to add iCarousel inside a tableview. I have followed http://ift.tt/1N9xH9e guide and amend it to iCarousel instead of collection view. Problem is the items in the iCarousel are not scrolling. Anyone tried same thing before? Please help.

enter image description here



via Chebli Mohamed

can I use UIDocumentPickerExtensionViewController without iCloud?


Actually I want to use google drive to store and access my files for my application. But I am not getting the how to do that without enabling iCloud. And also I am new to extensions and this document picker so it is already bit difficult to understand those things. sample codes will be easier to understand.



via Chebli Mohamed

Force a specific CLHeading value


In order to perform tests, I would like to force specific heading values to check if my app correctly processes them. Yet there are no instructions on the Apple website about how to manually create a CLHeading and the practice is even discouraged . Is there a way to do so or anyway to force CLLocationManager to deliver a specific heading value?



via Chebli Mohamed

Creating a iOS scrollable timeline view


I'm trying to create a timeline view in iOS that can be scrolled both horizontally (time) and vertically (cities). I'm having trouble finding if there is something made from before that I can look at for help.

The timeline view is a view that have date and time going horizontally and you can move time back and forward with moving finger on the horizontal axis. Vertically you can go future down to see the different rows (cities).

Timeline looks something like this:

Wed 4 Aug
---------
City A
01    02    03    04    ... time continues ->

City B
02    03    04    05

...(cities continue vertically)

What is the best approach to this? I been thinking about UIScrollView, but I have rows (cities) that need to be in place while changing the time.

I have experimented with UIView that has it's own drawRect but that seems less than brilliant to redraw each time user moves a little bit and sounds very heavy on the hardware.

I'm also thinking that different layers of UIViews could solve this, with top layer having the city names and the bottom layer being scrolled, but how could I solve the vertical scrolling?



via Chebli Mohamed

UIButton click event crash after adding the viewcontroller's view as a sub view


I want to add several ViewController's views as sub views of my another viewcontroller. So I have done like this inside my parent viewController.

-(void)MakeDisplayArea
{
vwDisplayArea=[[UIView alloc] initWithFrame:CGRectMake(0, 0, w, h-scrolTab.frame.size.height)];

[self.view addSubview:vwDisplayArea];
}





-(void)ProfClick :(id)sender

{

    [self MakeDisplayArea];
    ProfileViewController *profviewcontroller=[[ProfileViewController alloc] initWithNibName:@"ProfileViewController" bundle:nil];
    profviewcontroller.view.frame=vwDisplayArea.frame;
    [profviewcontroller.view setBackgroundColor:[UIColor clearColor]];
    [vwDisplayArea addSubview:profviewcontroller.view];

}

Then inside the profViewcontroller ViewDidLoad methods I am generating a button and set the target like this.

UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(10, 60, 100, 30)];
[btn setTitle:@"Button Test" forState:UIControlStateNormal];
[self.view addSubview:btn];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

-(IBAction)btnClick :(id)sender
   {

      NSLog(@"button clicked-------");
   }

I can see the button is appearing on that profViewcontroller that I loaded as a sub view, but when I click the button the app is crashing. What is the correct way add that viewcontroller as a subview on my first viewcontroller. Please help me.

Thanks



via Chebli Mohamed

Passing userID with photo POST Swift


I have an upload function that sends a photo to my server using a POST method. I now want to also include a variable userID (currentUser) in this service. I have the following code, but when i switch let param = ["userId" : "1"] to something like let param = [currentUser] i get an error. currentUser is declared as a String which is what the function calls for so I cant really figure out whats wrong.

func myImageUpLoadRequest(){
        let myUrl = NSURL(string: "http://ift.tt/1Hq3Qo1");

        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";

        let param = ["userId" : "1"]

        let boundary = generateBoundaryString()

        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

        let imageData = UIImageJPEGRepresentation(myImageView.image, 1)

        if(imageData==nil)  { return; }

        request.HTTPBody = createBodyWithParameters(param, filePathKey: "imagefile", imageDataKey: imageData, boundary: boundary)



via Chebli Mohamed

How to add UIButton Programmatically from a NSObject Class


I am trying to create a uibutton in a NSObject class. i get the error " Use of unresolved identifier 'view'". i figured that it needs to have UIViewController for it to work.

is there a work around so that i create multiple buttons with just this on multiple view controllers. what am i missing?

func createButton () {
    let button = UIButton();
    button.setTitle("Add", forState: .Normal)
    button.setTitleColor(UIColor.blueColor(), forState: .Normal)
    button.frame = CGRectMake(15, -50, 200, 100)
    view.addSubview(button)
}



via Chebli Mohamed