mardi 30 juin 2015

connect iPhone to Wifi enabled controller

I want to connect my iphone to wifi module residing inside a controller. can anyone tell me how i can make peer to peer connection with a wifi enabled controller.

I googled different communities and forums but couldn't get definitive answers.

Note:

1) There is no bluetooth or bluetooth smart available in controller.

2) Controller usually takes command from mobile phone and helps in operating home appliances.

Windows Phone Store & iPhone app store charges for listing app?

I would like to open account in windows phone store. What is the account opening fee. Is it one time fee or I had to pay annualy. Finnaly any discount available for opening account.

how to hide the status bar in iOS7?

In my application in ios8 status bar is hiding.But in iOS7 displaying the status bar. I have added the "Status bar is initially hidden = YES View controller-based status bar appearance = NO " and

[[UIApplication sharedApplication] setStatusBarHidden:YES
                                        withAnimation:UIStatusBarAnimationFade];

But getting the status bar.

Launch Apple Watch messages app from within another watchKit app

I want to launch the messages app on the Apple Watch from my own WatchKit app. I've seen this post here, but it only tells me to forward the app launch to the iPhone.

In the delegate method of the iPhone app, I can now perform a URL action. What's the URL I have to use in order to launch the messages app on the watch?

WatchKit Xcode 7.0 Beta 2 Build Error / Circular Segues / "exit code 255"

While working on a project for WatchKit 2 on XCode 7.0 beta 2, I have encountered the following build errors: enter image description here

Command /Applications/http://ift.tt/1CxB2sU failed with exit code 255

error: The folder “Interface.wkstoryboardc” doesn’t exist.

I had a storyboard with segues from view 1-2-3-4, with a final segue back from view 4-1. Each views controller had one button with a segue to the next view in the list.

enter image description here

Removing the segue from view 4 to 1 caused this error to go away. If this were an iPhone project, I would use an unwind segue. However, I cannot see how to do this on the watch. Has anyone else seen this behavior? Is this expected behavior, or a bug?

iOS App crashes on WLAN disconnect

I am facing a strange problem with my iOS app. It is written in Objective-C and i use iOS 8.3 on my testdevice (iPhone 4s). The app uses push notifications.

When I lock my iPhone, I sometimes get the following issue: Before unlocking the device again, the wlan status symbol in the status bar disappears and when I finally unlock it, the app freezes and I have to restart it (-> The WLAN sign returns and the app works without any problems)

How can I update a tableview cell from a -(void) method?

I am trying to update a specific dynamic cells font size from a -(void) method or some way without using cellForRowAtIndexPath. Is this possible?

Thanks

IBInspectable - Exposing the controls of a parent class

I want to create a IB_DESIGNABLE UIButton class to control the roundness of its corners but as stated by this question in order to control the button roundness I must change the corners of the button's view. In that case the poster creates a category.

I want to use the idea and create a UIButton class where I can control that.

But this is my problem: in order to Interface Builder show the exposed properties I have to create a UIButton class and assign that class to the button.

UIButtons inherit from UIView. The properties I want to expose are from UIView but that has to be done from the button class.

Any way to do that?

TableView with row inset

Is it possible to create such tableView?

enter image description here

It will have inset from first 2 row and the other row will be in full string

Can I resize a GADBannerView?

I'm using a custom GADBannerView in my application. Currently I'm getting the following frame.

<GADBannerView: 0x7fd146f9d8a0; frame = (0 0; 640 260); clipsToBounds = YES; layer = <CALayer: 0x7fd1455a2880>>

Can I resize the frame to 320x130? If I resize it I get a "No ads to display" error. If I keep it the original size I receive ads.

Is there is any way to change the size of GADBannerView?

Touch ID integration on iOS app

I am developing a new iOS app, on that if the user is idle for some time the app become locked and need to authenticate using Touch ID or password. This is the first time I am working with touch ID. Now I am facing some issues, they are :

  1. Can I use the Touch ID of my iPhone and the password of my app to unlock the app ? (That is when the app become locked the authentication alert will show, user can authenticate using Touch ID, or if the user taps on the "Enter password" option I need to navigate to another page of my app where the user authentication done by using the app password)
  2. Is it possible to remove the "cancel" button from the touch ID alertview ?
  3. On the first time the "Enter password" option on the touch ID alert is not showing. When I entered a wrong touch ID then from the next time onwards the Enter password option is displayed. (I didn't set any value for "localizedFallbackTitle")

Thanks in advance.

Why storyboard popover not working on device in Swift?

I have crated popover using storyboard, it working fine on simulator, But I am getting error on device, app get crash on device while popover

I am testing this on IOS7 device

Is there any solution for that?

Library to read and write XML in Objective C

I am new in IPhone developer(objective c) and I would like to know what is the best library to write and read XML file.

Dynamically change UIView frame and subview frame

I came across a problem when dealing with dynamically changing UIView's and subview's frame. Here is my below code.

I have 3 UI elements created in xib. dynamicView, dynamicLabel and a button. On button click, I am trying to resize the UIView's frame and UILabel's frame.

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *dynamicLabel;
@property (weak, nonatomic) IBOutlet UIView *dynamicView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.dynamicLabel.backgroundColor = [UIColor redColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)changeFrame:(id)sender {
    self.dynamicView.frame = CGRectMake(2, 2, 60, 60);
    //[self.dynamicView addSubview:self.dynamicLabel];
    self.dynamicLabel.frame = CGRectMake(0, 0, 30, 20);
}
@end

As per the code, the expected result is, the dynamicView resize to (2, 2, 60, 60) and the dynamicLabel which is a subview of dynamicView, resize to (0, 0, 30, 20) with respect to its superview, dynamicView. But in the actual result, dynamicView is resized correctly and dynamicLabel is resized with respect to self.view. Attached the screenshot. enter image description hereenter image description hereenter image description here

What am I missing to bring the expected result?

iPHONE: QR CODE GENERATION

I have a requirement to generate a QR code image which will return a string when scanned. I have completed the scanning of QR code.I need some suggestion on how to generate a QR IMAGE in Iphone.

how to calculate difference between two times in different dates in iOS?

starttime= 23:00 pm end time= 5:00 am

I need the summing time of the start time to end time i am trying this code but it is not helpful to me

NSDateFormatter *formatter = [NSDateFormatter new];
        [formatter setDateFormat:@"HH"];

        NSDate *currentTime = [NSDate date];
        NSDate *openTime = [formatter dateFromString:start];
        NSDate *closeTime = [formatter dateFromString:end ];
        NSCalendar *calender = [NSCalendar currentCalendar];
        NSDateComponents *currentTimeComponents = [calender components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:currentTime];
        NSDateComponents *openTimeComponents = [calender components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:openTime];
        NSDateComponents *closeTimeComponents = [calender components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:closeTime];

        NSUInteger currentTimeSeconds = currentTimeComponents.hour;

        NSUInteger openTimeSeconds = openTimeComponents.hour;

        NSUInteger closeTimeSeconds = closeTimeComponents.hour;

        if (currentTimeSeconds>openTimeSeconds && currentTimeSeconds<closeTimeSeconds) {
            NSLog(@"Time Between Open and Close Time %lu",(unsigned long)currentTimeSeconds);
        }

and it shows 0 hors. please help me some one? thanks in advance

UISplitViewController's preferredDisplayMode: incorrect behavior

I have a master-detail application (I created it using the Xcode template, and then I modified it a bit), and I'm trying to set the preferredDisplayMode property of UISplitViewController to obtain this behavior:

UISplitViewControllerDisplayMode.PrimaryOverlay: The primary view controller is layered on top of the secondary view controller, leaving the secondary view controller partially visible.

So the master view controller should initially be on top of the detail view controller, and it should be possible to dismiss it. I change this property in application:didFinishLaunchingWithOptions:, that's the full code:

 
// Inside application:didFinishLaunchingWithOptions:
// Override point for customization after application launch.
let rootViewController = window!.rootViewController as! UINavigationController
// The root view controller is a navigation controller that contains the split view controller
let splitViewController = rootViewController.viewControllers[0] as! UISplitViewController


let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self


splitViewController.preferredPrimaryColumnWidthFraction = 0.4 splitViewController.maximumPrimaryColumnWidth = 600 splitViewController.preferredDisplayMode = .PrimaryOverlay


return true

I have two problems: first, that's not the behavior that I obtain. The master view controller is hidden when the application launches, and if I click on the left bar button item to show the master, it rapidly appears and then disappears again. If I click it another time it appears without disappearing.
Second, I get a warning in the console:

2015-06-30 12:06:26.613 Presidents[29557:857547] Unbalanced calls to begin/end appearance transitions for <UINavigationController: 0x7b8be610>.

But I have no transitions in my code.

PS: It's from the book "Beginning Phone Development with Swift" by D. Mark, J. Nutting, K. Topley, F. Olsson, J. LaMarche, chapter 11.

Can I use the default image editor available in my iOS app?

I want to implement an image editing functionality similar to the native one provided by Apple in iPhones. Is it available to use inside the app? If not then is there any similar library available?

Testing IOS apps on ios devices made using IONIC and angularJS

I am making an app made using IONIC which i just want to test on my IOS device - not publish it to the app store. Do i still need a Apple developer account ( by paying $99 ) or is just a MAC with XCODE and IONIc installed enough?

I just want to test it on my device, not publish it to the app store.

Type 'ViewController' does not conform to protocol 'MPMediaPlayback'

I got this error message when trying to develop video player.

/Users/MNurdin/Documents/iOS/SwiftVideoPlayer/SwiftVideoPlayer/ViewController.swift:12:1: Type 'ViewController' does not conform to protocol 'MPMediaPlayback'

My code

import UIKit
import MediaPlayer

class ViewController: UIViewController, MPMediaPlayback { //error message here

    var isPreparedToPlay: Bool = true
    var currentPlaybackRate: Float = 0.0
    var currentPlaybackTime: NSTimeInterval = 0.0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func play() {

    }

    func pause() {

    }

    func stop() {

    }

    func prepareToPlay() {

    }

    func beginSeekingBackward() {

    }

    func beginSeekingForward() {

    }

    func endSeeking() {

    }

}

What I'm missing here? Please advice. Thank you.

Source code: http://ift.tt/1eXutLp

Reference: http://ift.tt/1FN2ovh

How to get url from video reference url

I have a url of video from photo library :-

assets-library://asset/asset.MOV?id=2EBD925F-D275-403E-A6A4-3487134D9B9D&ext=MOV

How can i get convert it to NSData I am tried following but nothing worked:

videoData = [NSData dataWithContentsOfURL:[[arrVideoUrl objectAtIndex:index] absoluteURL]];

iOS Credit Card Bill Payments Via Third Parties

I know that there are credit card services and APIs available for iOS that can be used for if we are selling any non-app related products of our own in our app, like bags, watches etc stuff like that. But can it be used for this scenario:

Bill Payment via a third party

where third party = a legal entity the pays around bills on behalf of its registered customers

the users scans his bills via the application and sends those scanned bills to the entity along with the payment of the bill from his credit card. And then the entity takes on the job from there and submits the bills to related departments (water, electricity, gas) etc.

I just want to know, if Apple can raise any issues with the app upon submission.

Should the entity be properly legalized to provide such services?

Anybody has any idea or thoughts about such a concept of an app?

Any help would be highly appreciated. Thanks!

Fetch Google plus friends who are following/like same page

I need to fetch the friends who are following the same page(profile) but I unable to get those friends. I have research thoroughly on google plus document but did not find any document related to my requirement. So any of you have faced the same issue before then please lead me in right direction.

Any suggestion would be appreciated.

how can logout from facebook in ios sdk

I have integrated Facebook login in my app and therfore user can login with both my app account and also Facebook and do corresponding actions.

  -(IBAction)FacebooklogoutBtnClick:(id)sender
  {
      FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];   
      [loginManager logOut];
  }

Run a operation throughout the application

I have a app in which I am logging some data constantly once started, now its limited to the same screen. I want to run that operation throughout the app irrespective of the screen I am in. User can start and stop in that particular screen.Also that operation should run when I suspended the app in background.

Email notification for Office 365 in jenkins ios build fails

When I try to build an iOS App with Jenkins , I got the error in Email notification for Office365 but for gmail I am able to get notification.

Error message: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM

Can you guys please help me , I was strucked since 1 week . Thanks

Compiler Warnings in Swift

How to add compiler warning in swift 2.

If i am not wrong Apple have not provide it yet, is there any best way to do so in mean time?

same for Errors?

Call JavaScript function from UIViewController class in iOS

I want to call javascript function from one of my view controller class,

here is my code snippet i have tried, but it is not working :(

Code in my ViewController

- (NSString *)MyMehtod{
    JSContext *context = [[JSContext alloc] init];
    JSValue *function = context[@"ProfilePicFunction"];
  [context evaluateScript: [self loadJsFromFile]]; //crashes here EXC_BAD_ACESS
     JSValue* result = [function callWithArguments:@[[documentsDirectory stringByAppendingString:@"/ProfilePic.png"]]];
    NSLog(@"res = %@",result);
}

- (NSString *)loadJsFromFile
    {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"app" ofType:@"js"]; //path returns here as nil
        NSString *jsScript = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; //jsScript returns here as nil
        return jsScript;
    }

Code in app.js file

function ProfilePicFunction(ProfilePicPath){
     var d= new Date();

    var userFullPath = ProfilePicPath+"?"+d.getTime();

    $("#userImg").attr("src",userFullPath);
}

Location of app.js Please help and thanks in advance!!

How to connect the audio to bluetooth when playing using AVPlayer

I am playing the audio from an url using AVPlayer, but when the iPhone is connected to a Bluetooth device it is not playing is Bluetooth, how to play via Bluetooth if it is connected, i see some posts in SO, but none of those are clearly explained. Below is my code.

    -(void)playselectedsong{

    AVPlayer *player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:urlString]];
    self.songPlayer = player;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidReachEnd:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:[songPlayer currentItem]];
    [self.songPlayer addObserver:self forKeyPath:@"status" options:0 context:nil];
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateProgress:) userInfo:nil repeats:YES];

    [self.songPlayer play];

}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if (object == songPlayer && [keyPath isEqualToString:@"status"]) {
        if (songPlayer.status == AVPlayerStatusFailed) {
            NSLog(@"AVPlayer Failed");

        } else if (songPlayer.status == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");


        } else if (songPlayer.status == AVPlayerItemStatusUnknown) {
            NSLog(@"AVPlayer Unknown");

        }
    }
}

- (void)playerItemDidReachEnd:(NSNotification *)notification {

 //  code here to play next sound file

}

UILocalNotification on Apple Watch - is it processed by Static or dynamic interface controller?

I have read the Watch Programming Guide in detail but am unable to find an answer to this question (the simulator isn't sufficient and I don't have an Apple Watch yet) -

1) Say, I trigger the following notification from the main app, will it be handled by the static notification controller or the dynamic notification controller on the Apple Watch?

var localNotification: UILocalNotification = UILocalNotification()
localNotification.alertAction = "Test Notification"
localNotification.alertBody = "Temporary Test Msg!"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 30) // 30 Secs
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

(I've added a functional Apple Watch target with all the required app icons.)

2) It's a simple text only notification and configured the Icons/Colours for the Static Notification Interface Controller in the story board. Will the watch pick these colors from storyboard?

3) Does PushNotificationPayload.apns play any role when this notification is triggered?

Can not play video fullscreen when rotate to landscape mode on Ios 8.1-8.2 using MPMoviePlayerController

In my application, I am trying to play a video in both landscape and portrait mode using MPMoviePlayerController. My present code is working completely fine in ios 7,ios 8.3 but in ios 8.1 and 8.2 the issue is that on changing the rotation of iphone/ipad to landscape, the video still runs in portrait mode in respect to that position and can not fullscreen. I've used a lot of solutions that I found on stackoverflow but can't fix this bug! This is my code

-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
if(IS_IPHONE) {
    BOOL rotation = [[NSUserDefaults standardUserDefaults] boolForKey:IS_KEY_FULLSCREENMOVIE];
if (rotation) {
    return   UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
    }
    return UIInterfaceOrientationMaskPortrait;
}
return UIInterfaceOrientationMaskAll;

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {


if(is_Portrait)
    [self performSelector:@selector(exitFullScreen) withObject:nil afterDelay:0];
else if (is_Landscape)
    if(IS_IPHONE)
        [self.moviePlayerController setFullscreen:YES animated:YES];
if (IS_IPAD)
    return YES;
return NO;

}

and

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
if(self.sideMenu.isOpen) {
    [self.sideMenu close];
}
if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
   toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
    [self loadGuiWhenLandScape];
}
else if( toInterfaceOrientation == UIInterfaceOrientationPortrait){
    [self loadGuiWhenPortrait];
}
[self setLayoutCell];
[_gridView reloadData];}

How to develop a network disk application.!

I haven't try this before.Is there any existing API ?And some ideas to do this!

Apple Watch: Can one Watchkit App communicate with more than one iOS App?

I'd like to write a Watchkit App that can communicate with more than one iPhone App.

For example, let's call this Watchkit App, "PingPong." All it does is set up an observer, and respond to a request--similar to an ICMP ping request. So, when an App sends a "PING" to the watch, the PingPong Watchkit app responds with "PONG."

How can I make this functionality accessible to multiple apps? In other words, I would like to expose this very simple interface, so that different apps can use it.

Note that the docs state, "You must have an existing iOS app to create a WatchKit app. The WatchKit app is implemented as a separate target of your Xcode project and is built and packaged inside your iOS app’s bundle... Xcode configures the targets for your WatchKit app and WatchKit extension and adds the needed files to your iOS project. The bundle IDs for both new targets are configured automatically, based on the bundle ID of your iOS app. The base IDs for all three bundles must match; if you change your iOS app’s bundle ID, you must update the other bundle IDs accordingly." http://ift.tt/1FfQqjr

This would imply that there's a 1-to-1 relationship between iOS extension apps and watchkit apps. Implication? Watchkit apps are essentially sandboxed, and this is not possible. But it couldn't hurt to ask. That's what SO is for, right? :P

Thx, Keith :)

How to send image to server using UDP Client Programm in iOS?

 - (IBAction)sendBuf:(id)sender
   {
    _imageVw.image=nil;

    if ([[bufOut text] length] > 0)
    {
        NSString *requestStr = [bufOut text];
        NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];
        [asyncSocket writeData:requestData withTimeout:-1.0 tag:0];//Writing to stream data
//        [asyncUDPSocket sendData:requestData withTimeout:-1.0 tag:1];
        [self debugPrint:[NSString stringWithFormat:@"Sent:  \n%@",requestStr]];
    }
    else
    {
        UIImage *image = [UIImage imageNamed:@"images.jpeg"];
        NSData *data = UIImagePNGRepresentation(image);

        _imageVw.image=[UIImage imageWithData:data];
        [asyncSocket writeData:data withTimeout:-1.0 tag:0];

    }
    [self startRead];
}

I have done this code for sending text & image . Text was sending successfully but image was not sending properly.I have done this demo from this here. I am unable to find where was the issue ? And the server was running in c# .net. It will handle both tcp & udp.

Javascript window.opener.location.reload() not working in ipad Chorme

I am using particular script.

<script>
  window.onload = function(){
  window.close();
  window.opener.location.reload();

};
</script>

Working on all browsers exclude in IPAD and IPHONE on chrome browser

Working Devices
1. Windows all devices and browser, 2. Android all devices and browser, 3. IOS desktop -Chrome, Safari, Mozilla Firefox

Not working 1. IPAD && IPHONE Chrome Only

What should i do for it ?

WatchOS2 network Communication

Do someone know if is possible with the new WatchOS2 manage for example an UDP listener (to receive and send data) directly from the Watch without use the iPhone as support? I have an App with an UDP listener that I would like to transfer in the Watch to avoid communication between the device. Thanks

Save received remote push notifications - ios

Can we save the received push notifications locally in a plist?

I have a reqiurment to show the number of unread push notifications in a badge view just like applicationIconBadgeNumber. But it should be shown inside the application, not as the icon badge view.

So, my question is can we save the received push notifications in all the status of the application(running, background and quit)?

I have implemented the push notifications, I can share the code if its necessary

send a dictionary in a soap service in ios

This is my code to send a dictionary to server but not able to do it. i am getting following message If you see this message then their are any problem in wcf service.

NSError * err;
    NSData * authData = [NSJSONSerialization dataWithJSONObject:[SharedGlobal SharedSingleton].dictAuthenticationNode options:0 error:&err];
    NSString * authString = [[NSString alloc] initWithData:authData encoding:NSUTF8StringEncoding];
    NSData * masterData = [NSJSONSerialization dataWithJSONObject:[SharedGlobal SharedSingleton].dictMasterNode options:0 error:&err];
    NSString * masterString = [[NSString alloc] initWithData:masterData encoding:NSUTF8StringEncoding];


    NSString *sSOAPMessage = [NSString stringWithFormat :@"<?xml version=\"1.0\" encoding=\"UTF-8\"?><soap:Envelope xmlns:xsi=\"http://ift.tt/ra1lAU\" xmlns:xsd=\"http://ift.tt/tphNwY\" xmlns:soap=\"http://ift.tt/sVJIaE\"><soap:Header/><soap:Body><Hotel_Features xmlns=\"http://tempuri.org/\"><XmlSearchRequest> {\"Hotel_Feature_RQ\": {\"HotelDetails\": { \"@HIndex\": \"%@\"}, \"Master\":\"%@\", \"Authentication\":\"%@\",}}</XmlSearchRequest></Hotel_Features></soap:Body></soap:Envelope>",hotelIndexNumber,masterString,authString];
    NSURL *sRequestURL = [NSURL URLWithString:@"http://myurl.asmx"];
    NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:sRequestURL];
    NSString *sMessageLength = [NSString stringWithFormat:@"%lu", (unsigned long)[sSOAPMessage length]];

    [myRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [myRequest addValue: @"http://ift.tt/1IIT7X1" forHTTPHeaderField:@"SOAPAction"];
    [myRequest addValue: sMessageLength forHTTPHeaderField:@"Content-Length"];
    [myRequest setHTTPMethod:@"POST"];
    [myRequest setHTTPBody: [sSOAPMessage dataUsingEncoding:NSUTF8StringEncoding]];

    [NSURLConnection sendAsynchronousRequest:myRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!connectionError) {

                NSString *responseString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSRange range1 = [responseString rangeOfString:@"<Hotel_FeaturesResult>"];
                if (range1.length !=0) {
                    responseString = [responseString substringFromIndex:(range1.location + range1.length)];
                    NSRange range2 = [responseString rangeOfString:@"</Hotel_FeaturesResult>"];
                    responseString = [responseString substringToIndex:range2.location];
                    NSData *apiData = [responseString dataUsingEncoding:NSUTF8StringEncoding];

                    handler(response,apiData,nil);
                }else
                    handler(response,nil,nil);

            }

    }];
}

Animate 3 lines into arrow in iOS for a uibutton

Does anyone know how to animate 3 parallel lines to a right arrow as happens in navigation menu bar to open up a side menu by applying CGAfflineRotation to 3 views .

I really need help on these as so that at-least I can get an idea to start it.

This is what it will be look like some how tried to draw it:-

_______                  
_______                        \
_______         to   ___________\
                                /
                               /

Any idea or suggestion will be helpful.

lundi 29 juin 2015

iOS : How to apply concave and convex effect on uiview?

I am working on an app where i have to open a camera and set surface view on it. That surface view will give concave or convex effect. Any help are most welcome.

Here i explained this two terminology:

A spherical mirror is said to be concave if the reflecting surface and the center of curvature (the center of the sphere of which the mirror forms part) are on the same side of the mirror; convex if the reflecting surface and the center of curvature are on opposite sides of the mirror.

enter image description here

Record video call in iOS webRTC based APP

I'm developing a webrtc based video call application in iOS. I want to record the call from the phone side through the app itself. How can I do this?

    //Create temporary URL to record to
NSString *outputPath1 = [[NSString alloc] initWithFormat:@"%@%@", NSTemporaryDirectory(), @"MyAudioRecord.mp4"];
NSURL *outputURL1 = [[NSURL alloc] initFileURLWithPath:outputPath1];

AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];

[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];

// Initiate and prepare the recorder
recorder = [[AVAudioRecorder alloc] initWithURL:outputURL1 settings:recordSetting error:nil];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[recorder prepareToRecord];

// Start recording
[recorder record];

I tried this. But its recording only the input audio. No output audio recorded.

AutoLayout not working in runtime iOS

I have a view, for which I have set the constraints using AutoLayout. After setting the constraints, the preview looks like what I need to have as given below. This is the preview

Now when I run the project in the simulator. The AutoLayout constraints seem to be not there. The views are not inj the same position as in the preview. Note: I have not made any dynamic changes to the views positions in the code. I hope so. Please help. Thanks in advance.

ViewController does not have a member named tipCalc

//
//  ViewController.swift
//  TipCalculator
//
//  Created by Mathias Bakken on 6/28/15.
//  Copyright (c) 2015 Mathias Bakken. All rights reserved.
//

I have 6-8 instances where I am receiving the error for not having the member tipCalc. I attempted to make an empty variable, but that only made things worse.

import UIKit

class ViewController: UIViewController {
@IBOutlet var totalTextField : UITextField!
@IBOutlet var servQualitySlider : UISlider!
@IBOutlet var foodQualitySlider : UISlider!
@IBOutlet var servQualityLabel : UILabel!
@IBOutlet var foodQualityLabel : UILabel!
@IBOutlet var resultsTextView : UITextView!
@IBAction func calculateTapped(sender : AnyObject){
    tipCalc.total = Double((totalTextField.text as NSString).doubleValue)
    let possibleTips = tipCalc.returnPossibleTips()
    var results = ""
    for (tipPct, tipValue) in possibleTips{
        results += "\(tipPct)%: \(tipValue)\n"
    }
resultsTextView.text = results
}
@IBAction func servQualityChanged(sender : AnyObject){
    tipCalc.servQuality = Double(servQualitySlider.value)/100.0
    refreshUI()
}
@IBAction func foodQualityChanged(sender : AnyObject){
    tipCalc.foodQuality = Double(foodQualitySlider.value)/100.0
    refreshUI()
}
@IBAction func viewTapped(sender : AnyObject){
    totalTextField.resignFirstResponder()
}
let tipCalc = TipCalculatorModel(total: 33.25, foodQuality: 0.06, servQuality: 0.06)

func refreshUI(){
    totalTextField.text = String(format: "%0.2f", tipCalc.total)
    foodQualitySlider.value = Float(tipCalc.foodQuality) * 100.0
    servQualitySlider.value = Float(tipCalc.servQuality) * 100.0
    foodQualityLabel.text = "Food Quality 1-10 (\(Int(foodQualitySlider.value))%)"
    servQualityLabel.text = "Service Quality 1-10 (\(Int(servQualitySlider.value))%)"
    resultsTextView.text = ""
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    refreshUI()
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

} I am getting a bunch of the same error messages saying "ViewController does not have a member named tipCalc"

I am also receiving the error "Use of unresolved identifier TipCalculatorModel"

How do I fix this issue? Thank you!

How to get a new iPhone app developed for the iPhone 5 to scale for the iPhone 6

Yes, I am literally doing the opposite of what everyone else was trying to do. I just developed an app and I don't want to worry about the constraints right now (we are internally testing). So I want the iPhone 5 version to just "automatically zoom" to work on the iPhone 6 and 6+ the way all apps did when the iPhone 6 was first released. Yes, I realize that the long term solution is auto constraints but for a quick prototype and iteration purposes this is the path I need to go down this week. By default when I run on an iPhone 6 I get all that extra space. I developed with target as ios 8.3 Xcode 6.3 Swift if that makes a different to anyone.

I have deleted the LaunchScreen.xib and used an asset folder as the Launch Image Sources. That asset folder looks like the following. enter image description here But when I run the app my iPhone 5 app doesn't scale to iPhone 6 size and instead I have a bunch of white space.

how to create my own radio buttons

I am new to Swift and Xcode so I need help with what I am doing. And what I am doing is this. I have three buttons one of them starts out checked. and what I want it to do is when I click on another button it checks it and unchecked the previous. I want my own radio buttons

WatchKit Xcode 7.0 Beta 2 Build Error / Circular Segues / "exit code 255"

While working on a project for WatchKit 2 on XCode 7.0 beta 2, I have encountered the following build errors: enter image description here

Command /Applications/http://ift.tt/1CxB2sU failed with exit code 255

error: The folder “Interface.wkstoryboardc” doesn’t exist.

I had a storyboard with segues from view 1-2-3-4, with a final segue back from view 4-1. Each views controller had one button with a segue to the next view in the list.

enter image description here

Removing the segue from view 4 to 1 caused this error to go away. If this were an iPhone project, I would use an unwind segue. However, I cannot see how to do this on the watch. Has anyone else seen this behavior? Is this expected behavior, or a bug?

nativeBounds of an iPhone 6 running in scaled mode?

What pixel sizes does UIScreen.mainScreen.nativeBounds return for an iPhone 6 which runs an app in scaled mode ie iPhone 5 mode?

Reference:

  • An iPhone 6 Plus returns 835x1482 pixels.
  • I don't have an iPhone 6 device at the moment so I cannot check.
  • Mr Google is quiet today.
  • The simulator returns completely different values for nativeBounds than devices do.

Swift Apple Pay Crashes; PKPaymentAuthorizationViewController = nil

I am trying to implement Apple Pay into my app. I've setup my merchant ID twice and I've installed Stripe, Stripe-Apple Pay via CocoaPods. Every time I try to run the app on my device it crashes. I've added breakpoints to try and understand where the error is occurring and I see the following when I get to the code applePayController.delegate = self

request PKPaymentRequest 0x00000001700f3180 0x00000001700f3180 applePayController PKPaymentAuthorizationViewController! nil None

Then the app crashes and I get this error message

function signature specialization of Swift.(_fatalErrorMessage (Swift.StaticString, Swift.StaticString, Swift.StaticString, Swift.UInt) -> ()).(closure #2) -> 0x100581474 <+44>: brk #0x1

Can someone help me figure out how to resolve this issue. Here is my code

import UIKit import PassKit

class DetailViewController: UIViewController {

let SupportedPaymentNetworks = [PKPaymentNetworkVisa, PKPaymentNetworkMasterCard, PKPaymentNetworkAmex]
let ApplePayMerchantID = "merchant.com.Flokk.FlokkV33"

var currentObject : PFObject?

@IBOutlet var EventName: UILabel!
@IBOutlet var EventTime: UILabel!
@IBOutlet var VenueName: UILabel!
@IBOutlet var Location: UILabel!
@IBOutlet var Description: UILabel!
@IBOutlet var EventImage: PFImageView!
@IBOutlet var PayButton: UIButton!

var ticketValue:NSDecimalNumber = 0.99

@IBAction func purchase(sender: AnyObject) {

    let request = PKPaymentRequest()
    let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request)
    applePayController.delegate = self

// presentViewController(applePayController, animated: true, completion: nil)

    request.merchantIdentifier = ApplePayMerchantID
    request.supportedNetworks = SupportedPaymentNetworks
    request.merchantCapabilities = PKMerchantCapability.Capability3DS
    request.countryCode = "US"
    request.currencyCode = "USD"

    request.paymentSummaryItems = [
        PKPaymentSummaryItem(label: "Test Ticket", amount: ticketValue),
        PKPaymentSummaryItem(label: "Flokk Event", amount: ticketValue)
    ]


}


override func viewDidLoad() {
    super.viewDidLoad()

    PayButton.hidden = !PKPaymentAuthorizationViewController.canMakePaymentsUsingNetworks(SupportedPaymentNetworks)

    if let object = currentObject {
        EventName.text = object["EventName"] as? String
        Description.text = object["EventDescription"] as? String
        VenueName.text = object["EventVenueName"] as? String
        Location.text = object["EventLocation"] as? String
        Description.adjustsFontSizeToFitWidth = true

        var initialImage = UIImage(named: "DidNotLoad")
        EventImage.image = initialImage
        if let parseEventPhoto = object["EventImage"] as? PFFile{
            EventImage.file = parseEventPhoto
            EventImage.loadInBackground()
        }

}

        }

} extension DetailViewController: PKPaymentAuthorizationViewControllerDelegate { func paymentAuthorizationViewController(controller: PKPaymentAuthorizationViewController!, didAuthorizePayment payment: PKPayment!, completion: ((PKPaymentAuthorizationStatus) -> Void)!) { completion(PKPaymentAuthorizationStatus.Success) }

func paymentAuthorizationViewControllerDidFinish(controller: PKPaymentAuthorizationViewController!) {
    controller.dismissViewControllerAnimated(true, completion: nil)
}

}

WKWebView stops working if interrupted

While working with WKWebView I have run into an issue where if the user taps a link before the page has fully loaded then the WebView stops working. You can test this with google news (phone) and when the first links load tap one. The loading process stops but the page is still interactive (scrolling works) but links do not and neither does LoadRequest:. It does not call the navigation delegate methods.

Swift segue fatal error

ViewController

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "Segue") {
        var svc = segue.destinationViewController as! ViewController2;

        svc.vericik = self.vericik

    }
}


@IBAction func gotoView2(sender: AnyObject) {
    self.performSegueWithIdentifier("Segue", sender: self)
    self.presentViewController(ViewController2(), animated: true, completion: nil)
}

ViewController2

var vericik: String!

    @IBOutlet weak var VeriYeri: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        VeriYeri.text = vericik
    }

When I click button on ViewController, ViewController2 page comes to screen and I can see segue data which come from ViewController. But after that, an error occurs: fatal error: unexpectedly found nil while unwrapping an Optional value

Where am I doing wrong?

Push Notification receive few times when app is in forground

I have currently developed an app in which push notification is used. Push notification received 100% when app is in background but notification received 50% when app is in foreground. Logic is same and this happen only on ipad mini. What could be the reason.

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.

AVPlayer not muting with silent switch state

I have a game which is using AVPlayer to stream remote tracks. This music is background audio in the game, so I need it to respect the silent/mute switch on the device.

Following Apple's documentation, I am doing the following:

NSError *error;
NSError *activationError;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryAmbient error:&error];
[audioSession setActive:YES error:&activationError];

AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:@"http://ift.tt/1qHOCFB"]];
self.player = [[AVPlayer alloc] init];

[self.player replaceCurrentItemWithPlayerItem:item];
[self.player play];

// error = nil, and activationError = nil at this point

I have tried this approach for both remote and local files. The files play and can be heard when the device is silent mode, whereas I'm expecting AVPlayer to mute the playback when the silent switch is on.

Quickblox Login name cannot displayed in the cell row

I have using Quickblox framework for chatting purpose.login value set to each cell.row. but some values displaying "0" in cell.row. I have attached the below images and shows login as a number and name. Below code the variable "testDict" return null value sometime.

    QBChatDialog *chatDialog = [ChatService shared].dialogs[idx];
    NSDictionary *testDict=[ChatService shared].usersAsDictionary[@(chatDialog.recipientID)];
    QBUUser *recipient = [ChatService shared].usersAsDictionary[@(chatDialog.recipientID)];
    NSString *test=recipient.login == nil ? (recipient.fullName == nil ? [NSString stringWithFormat:@"%lu", (unsigned long)recipient.ID] : recipient.fullName) : recipient.login;

    NSLog(@"DialogList:%@",testDict);

enter image description here

iOS Camera wobble from video recording

I'm having ONE single pain in the ass problem with recorded video from the iPhone.

Building a lap timer app for recording HD video on track days, I've eliminated the possibility of vibrations from wind, suspension and crucially the iPhone mount, so it must the the camera settings right?, I simply don't know what to change

Here's an example of the offending video 'wobble' at stand still (with iOS stabilization enabled), watch from 2:07s: https://www.youtube.com/watch?v=beair-rOMgw

Is it the autofocus?

  • Focus enum { AVCaptureFocusModelLocked = 0, AVCaptureFocusModeAutoFocus = 1, AVCaptureFocusModeContinousAutoFocus = 2

I used the following settings for video above

  • AVCaptureVideoStabilizationModeAuto:

It seem like there's software compensation for engine vibration/frequency at stand still, the lens (I know it's physically fixed) but some how is moving, I'm I crazy or what?

Can someone please guide me?

XCode Storyboard Issue

I cant see the Labels, Button etc in the View or their constraints though the Labels and Button appears on the side of the storyboard. And when you run the program in the simulator you can see that they are there. The project from my colleague who uses XCode 6.3.1 and I am using XCode 6.3.2 and he doesn't have this issue. When he updated his to to the same version I have he had the same problem; so he went back to the previous version 6.3.1. Now the problem persisted on my device even when I removed the 6.3.2 and substitute it with 6.3.1

stackoverflow prevented me from uploading the images but I can send it by email to anyone to see the screen shots

is there any open source library to convert doc file to p[df file in ios?

I want to generate a pdf file from an existing doc file? So there is any third party library available for this or any code?

iOS : Can I have two ECSlidingViewController Drawer from left and right?

I want to have two Drawer menus, one from left another from the right. Is it possible using ECSlidingViewController 2. If no then can you suggest the better way to achieve the same?

Storing an image as a profile picture

I already managed to load an image from the photo library. Now my question is, how can I store it permanently on the device that it is shown as profile picture?

The profile information, e.g. name or age, is stored on the device via NSUserDefaults.

Swift/SpriteKit - How to add points when an object collides with a player

I want to know how to give the player plus 1 point every time the player collides with that a certain object. Every time the object is collided with, it will at on to the previous amount. Example: if I have 5 coins and I collected 5 in this current game the overall amount of coins I will have is 10. It would be grate if you could link me to a place that has a tutorial of this in swift not in objective-c. Thanks!

Note: I have everything set-up with the coins spawning and the collision works but when the player collides the game ends.

Code, I have removed code that is not necessary:

import Foundation

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

    var movingGround: PPMovingGround!
    var square1: PPSquare1!
    var wallGen: PPWallGen!
    var diamondGen: PPDiamondGen!

    var isStarted = false
    var screenTapped = AVAudioPlayer()
    var isGameOver = false
    var isDiamondContact = false

    override func didMoveToView(view: SKView) {



        addMovingGround()
        addSquare1()
        addDiamondGen()
        addWallGen()
        start()
        addDiamondsLabels()



    }

    func addMovingGround() {
        movingGround = PPMovingGround(size: CGSizeMake(view!.frame.width, kMLGroundHeight))
        movingGround.position = CGPointMake(0, view!.frame.size.height/2)
        addChild(movingGround)
    }

    func addSquare1() {
        square1 = PPSquare1()
        square1.position = CGPointMake(70, movingGround.position.y + movingGround.frame.size.height/2 + square1.frame.size.height/2)
        square1.zPosition = 1
        playerNode.addChild(square1)
    }

    func addDiamondGen() {
        diamondGen = PPDiamondGen(color: UIColor.clearColor(), size: view!.frame.size)
        diamondGen.position = view!.center
        addChild(diamondGen)
    }

    func addWallGen() {
        wallGen = PPWallGen(color: UIColor.clearColor(), size: view!.frame.size)
        wallGen.position = view!.center
        addChild(wallGen)
    }

    func addDiamondsLabels() {
        let diamondsLabel = PPDiamondsLabel(num: 0)
        diamondsLabel.name = "diamondPointsLabel"
        diamondsLabel.alpha = 0.50
        diamondsLabel.position.x = view!.center.x - 120
        diamondsLabel.position.y = view!.center.y + 1000
        diamondsLabel.fontColor = UIColor.whiteColor()
        diamondsLabel.fontName = "Helvetica"
        diamondsLabel.fontSize = 40
        addChild(diamondsLabel)

        let diamondTotalLabel = PPDiamondsLabel(num: 0)
        diamondTotalLabel.name = "diamondHighscoreLabel"
        diamondTotalLabel.alpha = 0.50
        diamondTotalLabel.position = CGPointMake(view!.frame.size.width - 40, view!.frame.size.height - 60)
        diamondTotalLabel.fontColor = UIColor.whiteColor()
        diamondTotalLabel.fontName = "Helvetica"
        diamondTotalLabel.fontSize = 24
        addChild(diamondTotalLabel)

        let diamondTotalTextLabel = SKLabelNode(text: "Diamonds: ")
        diamondTotalTextLabel.alpha = 0.95
        diamondTotalTextLabel.fontColor = UIColor.whiteColor()
        diamondTotalTextLabel.fontSize = 22.0
        diamondTotalTextLabel.fontName = "Helvetica"
        diamondTotalTextLabel.position = CGPointMake(-90.0,2.0)
        diamondTotalLabel.addChild(diamondTotalTextLabel)
    }


    func start() {
        isStarted = true

        square1.stop()
        movingGround.start()
        wallGen.startGenWallsEvery(1)
        diamondGen.startGenDiamondsEvery(1)
    }

    func collisionWithDiamond() {
        isDiamondContact = true

    }


    // MARK - Game Lifecycle


    func gameOver() {
        isGameOver = true

        // everything stops

        square1.fall()
        wallGen.stopWalls()
        diamondGen.stopDiamonds()
        movingGround.stop()
        square1.stop()


        // create game over label
        let gameOverLabel = SKLabelNode(text: "Game Over!")
        gameOverLabel.fontColor = UIColor.whiteColor()
        gameOverLabel.fontName = "Helvetica"
        gameOverLabel.position.x = view!.center.x
        gameOverLabel.position.y = view!.center.y + 80
        gameOverLabel.fontSize = 22.0
        addChild(gameOverLabel)



    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    }

    override func update(currentTime: CFTimeInterval) {

    }



    // MARK: - SKPhysicsContactDelegate
    func didBeginContact(contact: SKPhysicsContact) {

        if !isGameOver {
            gameOver()
        } else {
            !isDiamondContact
            collisionWithDiamond()
        }

    }

Show segue inexplicably changes to a modal segue when a container view controller is used

I don't know the exact cause of this but I am guessing it has something to do with a container view controller being used. I am actually using several containers, one is for a SWRevealViewController, which houses a generic UIViewController for its rearViewController and a UINavigationController for the frontViewController. The root view controller of this navigation controller is another container view controller, a MainViewController, which contains a UIPageViewController. Page view controller has 3 UITableViewControllers and when I try to navigate from those table view controllers to the relevant view controllers, and I want it to be a push transition, it makes a modal transition so what gives?

It is something to do with hierarchy I guess, but it is kinda messed up with all these view controllers right now and I think I broke my brain at some point. I would really appreciate if someone who knows what is wrong can explain.

requestImageDataForAsset returns nil image data

I've been stuck with this for couple of days. I've bee trying to get the image within the call back but I always get nil. These the options which I used:

 let options = PHImageRequestOptions()
            options.deliveryMode = .HighQualityFormat
            options.resizeMode = .None

I also tried with options set to nil without any luck. This is the data I got in the info value passed to the block.

[PHImageResultIsInCloudKey: 0, 
 PHImageResultDeliveredImageFormatKey: 9999, 
 PHImageFileURLKey: file:///var/mobile/Media/DCIM/100APPLE/IMG_0052.JPG, 
 PHImageResultRequestIDKey: 84, 
 PHImageResultIsDegradedKey: 0, 
 PHImageResultWantedImageFormatKey: 9999,  
 PHImageResultIsPlaceholderKey: 0, 
 PHImageFileSandboxExtensionTokenKey: 
  64b47b046511a340c57aa1e3e6e07994c1a13853;00000000;00000000;0000001a;com.apple.app-sandbox.read;;00000000;00000000;0000000000000000;/private/var/mobile/Media/DCIM/100APPLE/IMG_0051.JPG]

I also tried using requestImageForAsset and I got the same result. I thought by using requestImageDataForAsset I'll get more control on the data.

Also, I thought the file exists in the cloud, but it is not as PHImageResultIsInCloudKey value is set 0; otherwise, I'd download it.

by the way, I am able to get a smaller version of the image with predefined size of 200x200 inside another view; however, when I try to get the larger version of it, I get nil. I know that the image exists on the phone with higher res (I can see it in the Photos app)

Any help will be appreciated.

jQuery AJAX multiple file upload not working on iPhone iOS8.3 but everywhere else

I implemented a multiple file uploading mechanism with jQuery and PHP. This is tested to be working on Linux/Windows Firefox, Chrome, IE, Opera, Chrome on Android and Windows Safari but not on iPhone 4g with iOS 8.3 and Safari?!

Since I am not the owner of the iPhone I cannot test by myself and I am not sure which browser is used ("I use the browser that came with it", the user says), I presume it is a mobile variant of Safari. Problem is, I really do not know what could be the fallpit of my code and how to debug or test it without an iPhone at hand?

Userstory:
User says that he is able to select a picture from his iPhone, it shows the progress bar that it is getting uploaded on the webpage and the page also says "Successfully uploaded" when it is done, but than the uploaded picture is never showing up anywhere. Like it is just vanished.

Here is some relevant code, maybe you see something that misbehaves or won't work on iPhones, I do not see.

If you got an idea on how to debug this on Linux, without an iPhone, be my guest to leave a comment.

Thank you in advance.

Relevant Javascript:

var uploadFile = function () {

var subdir = $('#subdir').val();
var fileType = $('#fileType').val();

var data = new FormData();

jQuery.each($('#file')[0].files, function (i, file) {
    data.append('file-' + i, file);
});

data.append('subdir', subdir);
data.append('fileType', fileType);
$.ajax({
    url: reLangUrl + "files/index?uploadFile",
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function (html) {
        console.log('file Upload success!');
        $('#selectFileContent').replaceWith(html);
        modules.files.handlers();
        modules.files.selectClickHandler();
    }
    ,
    progress: function (evt) {
        if (evt.lengthComputable) {
            var percent = parseInt((evt.loaded / evt.total * 100), 10) + "%";
            $('#uploadProgress > span').html(percent);
            $('#uploadProgress').css('width', percent);
            //console.log("Progress: " + parseInt( (evt.loaded / evt.total * 100), 10) + "%");
        }
        else {
            console.log("Progress: Length not computable.");
        }
    },
    progressUpload: function (evt) {
        if (evt.lengthComputable) {
            if ($('#uploadProgress').hasClass('hidden')) {
                $('#uploadProgress').removeClass('hidden');
            }
            var percent = parseInt((evt.loaded / evt.total * 100), 10) + "%";
            $('#uploadProgress > span').html(percent);
            $('#uploadProgress').css('width', percent);
            //console.log("Upload " + parseInt( (evt.loaded / evt.total * 100), 10) + "%");
        }
        else {
            console.log("Upload: Length not computable.");
        }
    }
});
}

PHP Code:

private function uploadFile($fileType, $subdir = "") {

$n = 0;
$filesUploaded = 0;
while (isset($_FILES['file-' . $n]) && is_file($_FILES['file-' . $n]['tmp_name'])) {
    $currentFile = $_FILES['file-' . $n];
    if ($fileType == 'image') {
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        if (false === $ext = array_search(
                $finfo->file($currentFile['tmp_name']), array(
            'jpg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
                ), true
        )) {
            //throw new RuntimeException('Invalid file format.');
            echo "<div class='error'>" . $this->ts("Invalid file format. Only jpg, png and gif is allowed.") . "</div>";
            unset($currentFile['tmp_name']);
            return;
        }
    }

    $sh = $this->loadHelper('Session');
    $id = $sh->get('uid');
    if (substr($subdir, -1, 1) != "/") {
        $subdir .= "/";
    }
    $target_dir = "upload/users/" . $id . "/" . $fileType . "s/" . $subdir; //$sh->get('uid');
    $target_path = $target_dir;
    if (!is_dir($target_path)) {
        mkdir($target_path, 0777, true);
        chmod($target_path, 0777);
    }
    $filename = basename($currentFile['name']);
    $target_file_path = dirname(__FILE__) . '/../../' . $target_path . $filename;
    if (move_uploaded_file($currentFile['tmp_name'], $target_file_path)) {
        chmod($target_file_path, 0777);
        //echo "<div class='system'>" . $this->ts("File uploaded successful") . "</div>";
        ++$filesUploaded;
    } else {
        //echo "<div class='error'>" . $this->ts("Error uploading Image.") . "</div>";
    }
    ++$n;
}
if ($filesUploaded > 0) {
    echo "<div class='system'>" . $filesUploaded . " " . $this->ts("file(s) uploaded successful") . "</div>";
} else {
    echo "<div class='error'>" . $this->ts("Error uploading file(s).") . "</div>";
}
return;
}

And finally the HTML Form:

    <div class="uploadFilesForm">

    <div class="help">
        <?php echo $this->ts('Only jpeg, png and gif files allowed!'); ?>
    </div>

    <form class="pure-form" action="<?php echo $this->action("files/index") ?>" method="post" enctype="multipart/form-data">

        <input id="subdir" name="subdir" type="hidden" value="<?php echo $subdir ?>" />
        <input id="fileType" name="fileType" type="hidden" value="<?php echo $fileType ?>" />
        <label for="file" ><?php echo $this->ts("upload " . $fileType) ?></label>
        <input class="pure-button" id="file" name="file[]" multiple="multiple" accept="<?php echo $fileType ?>/*" type="file"/>
        <a class="pure-button pure-button-primary" id="uploadFile" onclick="return false;" name="uploadFile" >
        <?php echo $this->icon('mono/white/16x16/round_and_up.png');?>&nbsp;
        <?php echo $this->ts("upload") ?>
        </a>
    </form>
    <div id="uploadProgress" class="hidden"><span class="percent">0%</span></div>
</div>

How to done pagination in table view??

My problem is a i am doing this using tableview delegate(scrollviewdidscroll:) but when i am scroll down next object is reload but then scroll up same object r shown in first page which is shown in last page. I am using static array any store this object are store in a mutable array.

I have to show per Page 10 elements.

If 14 element first page shown 10 element and next page shown 4 element.

In my program first page show 10 element but next page show 14 element and then first page is also shown 14 element.

I am using xcode 6.1

How i am solve this problem?? thanks in advance..

How to put a Bar button item to the bottom of a toolbar?

I have a toolbar at the top of my app. I changed the height programmatically to make it a bit bigger.

    var constH = NSLayoutConstraint(item: toolbar, attribute: NSLayoutAttribute.Height,
    relatedBy: NSLayoutRelation.Equal, toItem: nil, 
    attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 64)
    toolbar.addConstraint(constH)

But now I have the problem when I add bar button items via storyboard, it automatically centers them vertically. Only the standard items stay at the bottom. How to solve?

[Please answer in Swift]

enter image description here

Using UIScrollView to cycle through images

Storyboard view of controller

I have an imageView inside of a scrollView, and I want to be able to upload up to 3 images and have the user swipe between them. I have accomplished this simply by replacing the contents of the view with the information I want, but it doesn't look or feel as good as a scroll view with pagination would.

I have all of the code to make each image appear when I want it, but my problem is with the scrollview constraints and how to add more content to a scrollview with fixed width. No matter what I do, I can't seem to extend the scroll range when I add an image to the view.

here is what I'm trying now:

let newImageView:UIImageView = UIImageView()
self.imageScrollView.contentSize = CGSize(width: self.imageView.frame.size.width * 3, height: self.imageView.frame.size.height)
self.imageScrollView.pagingEnabled = true

for i = 0; i < 3; ++i {
    var xOrigin:CGFloat = CGFloat(i) * self.view.frame.size.width
    newImageView.frame = CGRectMake(self.imageView.image!.size.width * i, 0, self.imageView.image!.size.width, self.imageScrollView.frame.size.height)
    newImageView.image = images[i]
    newImageView.contentMode = UIViewContentMode.ScaleAspectFit
    self.imageScrollView.addSubview(newImageView)
}

With this code I am able to add the images, but I cannot scroll to them. In my storyboard, the scrollview constraints look like this:

enter image description here

I'm sure some of these constraints are redundant, but I can't figure out why the content width won't extend and allow me to scroll through all of the images in the scrollview.

App Invites with Facebook on iOS App

I'm trying to set up App Invites on an iOS app I developed. However, when I invite others to use the app, they do not get any notifications.

Right now, the App Link I obtained redirects me to a link starting with itunes.apple.com, but the screen is blank. In addition, when I run the didCompleteWith Results function, I get "didComplete = 1;". I am not sure why the invitation is not working and why the person on the other end is not getting a notification. I have a hunch it could have to do with my App Link, but I am honestly not sure at all. I am trying to use Facebook's purely Mobile API since I do not have a website for my app. Also, it is not released on the App Store.

Any and all help is greatly appreciated.

Thanks!

Can I resize a GADBannerView?

I'm using a custom GADBannerView in my application. Currently I'm getting the following frame.

<GADBannerView: 0x7fd146f9d8a0; frame = (0 0; 640 260); clipsToBounds = YES; layer = <CALayer: 0x7fd1455a2880>>

Can I resize this to 320x130? I can't resize this. If I resize it I got "No ads to display" error.

If I give original size I got ads.

Is there is any way to change the size of GADBannerView?

UILabel inside a View scrolling being truncated

I am using a UILabel to scroll text inside a small view, this scrolls and then repeats after some time. What happens now, is the length of the text, becomes truncated, so instead of the full name showing, it shows xxxxxxxxxx then .. at the end, is there a way to extend it, so it shows the entire text without truncating?

-(void)text_1_Move_animetion
{
    text_1_lable.frame = CGRectMake(text_1_lable.frame.size.width, text_1_lable.frame.origin.y, text_1_lable.frame.size.width, text_1_lable.frame.size.height);

    [UIView animateWithDuration:8.0 animations:^{
        text_1_lable.frame = CGRectMake(-text_1_lable.frame.size.width, text_1_lable.frame.origin.y, text_1_lable.frame.size.width, text_1_lable.frame.size.height);
    }];
    [self performSelector:@selector(text_1_repet) withObject:self afterDelay:8.0];


}
-(void)text_1_repet
{
    text_1_lable.frame = CGRectMake(text_1_lable.frame.size.width, text_1_lable.frame.origin.y, text_1_lable.frame.size.width, text_1_lable.frame.size.height);


    [UIView animateWithDuration:8.0 animations:^{
        text_1_lable.frame = CGRectMake(-text_1_lable.frame.size.width, text_1_lable.frame.origin.y, text_1_lable.frame.size.width, text_1_lable.frame.size.height);
    }];


    [self performSelector:@selector(text_1_Move_animetion) withObject:self afterDelay:8.0];
}

If I set the linebreak within the .xib file to 'break' it does not truncate with a .. It shows a bit more, but then cuts off towards the end.

Big delay between getting data and setting it as UILabel Text [duplicate]

This question already has an answer here:

I get currency rate using this code.

let USDAUD = NSURL(string: "http://ift.tt/1Hse127")

    let task = NSURLSession.sharedSession().dataTaskWithURL(USDAUD!) {(data, response, error) in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
        if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
            let exchangeRate = string.componentsSeparatedByString(",")[1].doubleValue
            self.displayValue.text = "\(exchangeRate)"
        }
    }

    task.resume()

But delay between getting data and setting as a label text is too high. What should i do?

Open an app on battery notification

I'm looking for a way to open (or display a notification from) an iphone app when a low battery level notification occurs. Is it possible to perform it if my app is running in background ? I found that an app can't refresh after some minutes in background, but I wonder how many apps can display notifications by their own without being opened.

Thanks.

xcode ios App "The application could not be verified"

I'm developing a app with the latest xcode. I configured xcode to "don't sign" to install the app to my iphone without a developer account. It was working fine, until i updated my iphone 6 to ios 8.3.

I removed the app from the phone, restarted it, did a "clean"(in Build-Menu), but same error.

Also i havent changed the project settings in xcode.

Enterprise Certificate Apple

I'm using enterprise certificate of apple and I create an application using that certificate.Peoples are using the app.problem is,enterprise certificate is going to expire in next month and I want to renew it.can anyone tell me what should I do? and are there any issues on app if I do not renew it? and after renew the certificate?

IOS Swift splash screen from Storyboard

In my Iphone app need to display a splash screen (displays company logo and some info) for 2-3 seconds before load the first page.

Also the app needs to decide which page should load as the first page in here (according the 'initial setup completion' level by the user).

I am using 'Swift' as the programing language and 'Universal StoryBoard' to design interfaces...

I have seleted the Main.storyboard as the Launch Screen File. In the ViewController class have implemented following logic

override func viewDidAppear(animated: Bool) {
    NSLog("_______Before sleep_______")
    sleep(2)
    NSLog("_______After sleep________")

    self.controllNavigation()
}

func controllNavigation() -> Void {

    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    var nextViewController  

    if (Condition1)
    {
        nextViewController = storyBoard.instantiateViewControllerWithIdentifier("MainMenu") as! MainMenuViewController
    }
    else
    {
        nextViewController = storyBoard.instantiateViewControllerWithIdentifier("UserSetup") as! UserSetupViewController
    }

    self.presentViewController(nextViewController, animated: true, completion: nil)

}

All works ok but While waiting with sleep(2), refresh page sort of a thing happens. I am not sure if this is the best way to do. Like to hear ideas. Thanks

iOS exposure algoritm

I need implement camera exposure change for video recording. I look for default autoexposure:

_device.exposureMode = AVCaptureExposureMode.ContinuousAutoExposure

It works fine. But I need more complicated logic with exposure and wide range of Exposure time change [0.01, 0.8]. Default algorithm have [0.01, 0.25] of Exposure time range. So I try to repeat apple algorithm. I know when image might be lighter or darker, but I need implement some logic for ISO and Exposure time change. I already implement my algorithm but it works not how I need.

Some result of experiments with standard algorithm (I capture standard exposure change when environment light change; exposure scaled for normal display on chart): enter image description here

Get location in background AND when app is terminated

Is there a way to get

1. Location notification when the app is in the background

2. Location notification After the app is terminated

3. When terminated - get the location notification for movement of less than 500 meters

ALL IN SAME APP?

(i've seen articles that says you should use

[myLocationManager startMonitoringSignificantLocationChanges]; 

INSTEAD of -

[myLocationManager startUpdatingLocation];

can i use both?)

thanks

PhoneGap app (for apple) doesn't work

I am new to phonegap and coding so I am unaware as to how to use PhoneGap. First of all what I did was connect my PhoneGap (desktop) app thing to my iPhone PhoneGap developers app. On my iPhone it just says downloading... there is nothing else happening. I then tried using an Android phone to see if it works but it just says

unable to download archive from the server.
unable to properly connect to the server. 

I dont know what to do so any help will be appreciated.

How to integrate deeplink ios & android

I am trying to integrate deep link in our application.

My requirement is : Need to open app directly from mail, if the app is installed, or directly navigate to App Store/ Play store based on device (iOS/Android). It should work if the device is offline too. so i don't want to use any html in between.

URL identifier :  net.company.application
URL Schemes : application
URL (which is add to the mail) : application://opendetails/001

Please help me to achieve this. Thanks in advance

Chat application Integration in IPhone using Objective C

I created an application where user can chat with Trainer at any time. I need a medium to send and receive messages like instant messenger. I don't want to buy third party SDK's , because I need to store all messages and attachments in my server DB.

I searched in google, every chat app was integrated through parse or push notification . Will that give more convenient integration procedure? But from my studies, notification willn't help for chat, because If APN server has multiple messages in queue it'll send only the latest one, Finally I will lack my past messages.

  1. I need a class files or anything to communicate between two users.

  2. Need notification for new messages.

  3. Want to store all chats in my server DB.

Is this requirement sounds good??? If possible can you please help me to find out the way?

Custom ads in AdMob?

I want to know that how to display custom ads in Google AbMob? i want to display custom ads in AdMob, is it possible? if not than can you please suggest me show the other ways to display custom ads.

Web Application not working in iphone with ATnT connection

I ran into a strange issue with a web application. It is on http protocol and hosted in amazon EC2 server. It is smoothly accessible from all phones and networks, except iphone with ATnT network.

I have even tried this stackoverflow solution :

Header set Cache-Control "no-transform"

But still facing the issue with loading web application with iphone and ATnT.

subview load from xib,reload view frame, but viewsubviews not change frame

  • (void)viewDidLoad {

    self.buttonSubView=(EventbuttonsView *)[[NSBundle mainBundle] loadNibNamed:@"ActionHeadView" owner:nil options:nil][1];

    [self.buttonSubView setY:self.view.frame.size.height-130];

    [self.buttonSubView setWidth:self.view.frame.size.width];

    self.buttonSubView.backgroundColor=[UIColor redColor];

    [self.view addSubview:self.buttonSubView];

    [self.buttonSubView layoutIfNeeded];

}

buttonSubView is a customview, It's subviews use autolayout , when i call [self.buttonSubView layoutIfNeeded], but subviews donot update frame? why? in xib i use update frame, it is ok.but run in iPhone,cannot work?

Quickblox Login name cannot displayed in the cell row

I have using Quickblox framework for chatting purpose.login value set to each cell.row. but some values displaying "0" in cell.row. I have attached the below images and shows login as a number and name. Below code the variable "testDict" return null value sometime.

    QBChatDialog *chatDialog = [ChatService shared].dialogs[idx];
    NSDictionary *testDict=[ChatService shared].usersAsDictionary[@(chatDialog.recipientID)];
    QBUUser *recipient = [ChatService shared].usersAsDictionary[@(chatDialog.recipientID)];
    NSString *test=recipient.login == nil ? (recipient.fullName == nil ? [NSString stringWithFormat:@"%lu", (unsigned long)recipient.ID] : recipient.fullName) : recipient.login;

    NSLog(@"DialogList:%@",testDict);

enter image description here

inAppPurchase in ios SDK using xcode6

I want to test in-App-Purchase

What I have done:

1.Created Certificate/AppId/Provisioning

2.Bundle Id of my app : com.sample.product

  1. Set Up an app in itunesConnect.

  2. product Identifier of my app which i have to buy: com.sample.product.buy

I have followed and implemented all steps from here:

steps i followed

No I get NSLog value : Product Not Availabel

I checked for issues like:

  1. Different product id
  2. Cleared for sale
  3. Waited 4 days

Why I am getting this error? What I missed?

When I open app in itunes.connect and select In-App-Purchase am getting this message at the top of screen:

enter image description here

Is it OKAY ? Or due this warning message I am getting Product Not Available message ?

How can I start developing app in swift. How to manage different screen size of iPhone 5, 6 and 6+

I am novice iOS developer. And I have done some iOS app for iPhone 5 using objective-C. Now how can I manage different screen size for iPhone 5, 6 and 6+. which screen size works for every iPhones. Or which way works better for all versions.

Testing In App Purchases - Cannot Connect to iTunes Store

I'm returning to some code I wrote in 2012. Back then, I had created a wrapper for the StoreKit framework that also did receipt validation using the sandbox URL for iTunes.

Since it's been so long, I looked through the StoreKit docs and AFAIK, nothing's changed.

For some reason, I can't test my In App Purchases anymore because I get the above error (Cannot Connect to iTunes Store) and the sandbox servers seem to be down (http://ift.tt/1fKihJh).

It's been down for the past 2 days. Is this normal? Or has the process for testing changed since when I first wrote this code?

Best method to resize UIView when rotated to landscape and back

Since I am very new to ios programming I have more of a general-design question. I have a ViewController which contains a GraphView (UIScrollView + UIView) which works fine. When I am rotating to landscape I want the GraphView to resize its height to the display height (so it fills the whole screen) but only 300pts when in portrait.

What I did so far is implementing viewWillLayoutSubviews in the ViewController and resetting the constraints:

- (void)viewWillLayoutSubviews{        
_graphViewHeightConstraint.constant = ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) ? 300:[[UIScreen mainScreen] bounds].size.height-self.navigationController.navigationBar.frame.size.height - 2*_distanceToTopView.constant; 
}

and in GraphView.m:

- (void)layoutSubviews{
kGraphHeight = self.frame.size.height;
[self setNeedsDisplay];  
}

(because I need the variable kGraphHeight in the code to draw the Graph). This does not seem like a very elegant solution so I wanted to ask what the better way would be? Many thanks for your inputs :)

Table View not showing titles

I'm developing my project on swift and create a simple table view with one cell, then i created a label, but it's not showing. What's the problem and how to fix it?

programatically select all text in UITextView

I made a TextView that is filled with several sentences. So I want when the user click on it to be considered as one object. If the user click on any word in the text, I want the whole text to be clicked.

Which is better block or delegate?

Apple is constantly changing most of the existing codes which were in delegate form now to block.

I always have a confusion that where to use block and where to use delegates?

Even I always feel that its better way to provide abstraction if we use delegate instead of block. Just want to hear other developers view in this topic. If it seems very foolish topic pardon me.

How to control More navigation controller in tab bar controller

In my application I have a tab bar controller which has been pushed into a navigation controller as it is the third screen of the application. For that I have added a tab bar controller in my story board and created a View controller for that ,which is a sub class of UITabbarcontroller.Then I wrote the following code to push the tab bar controller into the navigation controller.

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UITabBarController *obj=[storyboard instantiateViewControllerWithIdentifier:@"tabBarCon"];
            obj.selectedIndex = 2;
            obj.tabBarItem.title = @"Next Screen";
            [self.navigationController pushViewController:obj animated:YES];

I have 6 tabs in my tab bar.So the last two tab bar items appears in More navigation controller.I have added separate navigation controllers for all the view controllers in tab bar controller.My problems are:

I am not able to set a title for More navigation controller screen , which displays the last two tab bars in a table view.Title is coming as the title of last visited view controller.And When I go back from any of these two view controllers I am directly coming back to my second screen instead of going back to More navigation controller.

Please suggest on this.Please correct me if I am doing anything wrong.

How to reconnect to open fire server after unlocking the iPhone screen?

I am using XMPPFramework. My XMPP connection is always closed when I locked the iPhone screen. I need to reconnect to my open fire server when I unlock the screen.

Here is how I used XMPPReconnect (in Swift):

func xmppStreamDidAuthenticate(sender: XMPPStream) {
    let xmppReconnect = XMPPReconnect()
    xmppReconnect.activate(sender)
    xmppReconnect.addDelegate(self, delegateQueue: dispatch_get_main_queue())
}

However, it seems it never reconnects when I unlock the screen. Am I using XMPPReconnect correctly?

How do I achieve my target?

Add iOS Certificate - The Generate button is disabled

I am trying to generate a certificate for my new iPhone app. I already did it before and had no problem. Now when I try it, the "Generate" button is disabled. I read in a stackoverflow soultion, that I can create only one certificate Cannot create a distribution certification in Apple Developer website (although I had 3), so I deleted (Revoked) all of them. It didn't help, and now I have no certificates.

iOS Mirroring MPMoviePlayerController to TV with TV screen playback in fullscreen

I have an App with video (locally stored) playback using MPMoviePlayerController

    NSString *deviceDir = [[NSUserDefaults standardUserDefaults] stringForKey:WZLDEVICEPATH];
NSString *videopath = [deviceDir stringByAppendingPathComponent:video]
NSURL *url = [NSURL fileURLWithPath:videopath];
player = [[MPMoviePlayerController alloc] initWithContentURL:url];
CGRect viewInsetRect = CGRectInset (playerframe,
                                            0.0,
                                            0.0 );
        /* Inset the movie frame in the parent view frame. */
[[player view] setFrame:viewInsetRect];
[player view].backgroundColor = [UIColor clearColor];
[player view].tag = TAG_VIDEO_PLAYER;
player.movieSourceType = MPMovieSourceTypeFile;
[player prepareToPlay];
[self.view addSubview: [player view]];

Now I need to mirror the App to an external device, the mirroring just works fine to the second screen (TV), but the TV playback is in the same resolution(width x height) as it is in the iPad, I have to make the TV playback in fullscreen. Is there any way to make sync playback in two devices at different resolution.

I have tried for the multiple window with different instance of MPMoviePlayerController but there the sync playback is getting affected. Is there some work around to overcome these issues?

How to develope IP Messenger in iOS?

I am doing small demo on IP messenger in iOS using Objective-C. Can anyone help me how to do this ? The server side was developed in C#.Net. So I have to communicate with that server like IP Messenger. How can I approach ? Is there any demo projects in github or any othger place ?

dimanche 28 juin 2015

How can I capture text input dialogue in a tex input popup box on iPhone? i.e. name and email

In my app, when the user taps a button a number will decrease until it hits zero. When the number hits zero I want to display an input popup box for the user to put their name and email. I then want to be able to capture this information, as the developer, so that I can then be able to contact the user of my app. Thanks for the help!

How to design iOS in landscape mode for all devices in xocde 6?

I want to design the iOS devices screen for landscape only.I have tried going to Attribute inspector->Orientation->Landscape but screen is always visible in portrait mode.From bottom i have tried changing the size classes but i don't get any option for designing in landscape mode only for all devices.Please suggest me how to do this?

Custom View Controller on launching

After a few years off the grid, I'm back programming a quick IOS application and I have to say it seems I need to get back on track :D

I'm just trying to set-up a login view upon launching the application and I am stuck with the following issue on which I've read about a lot but could not fix it. Simulation stops on the main.m (@autoreleasepool). FYI, I am not using xib or storyboard as I'm trying to do everything programmatically.

libc++abi.dyLibL terminating with uncaught exception of type NSException

It is probably coming from one of the following. LoginViewController.h

@interface LoginViewController : UIViewController 
@end

Test1 / LoginViewController.m I guess there should be a init method defined from UIViewController so I would not need to define one here.

@implementation LoginViewController
@end

Test2 / LoginViewController.m Trying to override with my custom init function. No luck as well.

@implementation LoginViewController
- (id) init
{
self = [super initWithNibName:nil bundle:nil];
return self;
}
@end

AppDelegate.m (didfinishlaunching function)

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
LoginViewController *loginViewController = [[LoginViewController init] alloc];
// error here
self.window.rootViewController = loginViewController;
[self.window makeKeyAndVisible];
return YES;

Not sure exactly what went wrong here but it crashes right after seeing a black iphone screen on the simulator... Any help appreciated ;)

Thanks.

Google Maps fill full screen. How to fill it to half screen?

I use the next code:

var camera = GMSCameraPosition.cameraWithLatitude(40.378259,
        longitude: 49.875059, zoom: 16)
    var mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
    mapView.myLocationEnabled = true
    self.view = mapView

    var marker = GMSMarker()
    marker.position = CLLocationCoordinate2DMake(40.378259, 49.875059)
    marker.map = mapView

and I use constraints, but it doesn't helps me. My map fills full screen, even if I do the next:

var mapView = GMSMapView.mapWithFrame(CGRectMake(0, 0, 100, 100), camera: camera)

Why it doesn't work? How can I fix it? I connect it by Podfile

How to manage network communication in iOS using tcp/udp?

I have tried this demo project. It is working great. I able to send text and image.But the problem was data is able to see after closing the application, then only I will be able to see the image .

Xcode "switch/case" statement - warning about break;

What constantly happens to me is this, when I'm using Xcode with Objective-C:

I'll be writing a switch/case statement. Typically, to make sure statements are separated, the programmer must make sure there are break;s between cases.

I often forget to put the break; statement in, so instead of the device executing only the the desired case, the device executes the case and then the case after it. This happens on both a physical device (iPhone 6) and on every simulated device on iOS Simulator.

Here's what the syntax of the failed statement looks like, with someInt being a number that is either 0 or 1:

switch (someInt)
{
    case 0:
    {
         // some statements to execute if "someInt" is 0
    }
    case 1:
    {
         // some statements to execute if "someInt" is 1
         break;
    }
}

Note how, in case 0:, there is no break; statement. This causes case 0: to execute and then case 1 to execute, instead of just case 0 to execute.

Is there a way I can put a flag in Xcode so it warns me if I forget a break; statement?

I know many programmers have probably been confused for days, weeks on end, because of this problem.

Call and use uitableview from uitableviewcell?

I have a UITableViewController with many UITableViewCell. Each Cell have a UISwitch Button.

Here is my UITableViewController Class:

@implementation DanhsachTableViewController{
    NSMutableArray *data;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
}

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        DichVu2TableViewCell *cell = (DichVu2TableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"dscell"];
        NSDictionary *dataCell =  data[indexPath.row];
        cell.service =  dataCell[@"service"];
        cell.package =  dataCell[@"package"];
        cell.loai_goi = dataCell[@"loai_goi"];

        return cell;
    }
-(void) changeCellState:(NSString *)service package:(NSString *)package loaigoi:(NSString *)loai_goi{
    for (int i =0;i<data.count;i++){
        DichVu2TableViewCell *cellLocal = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        if ([service isEqualToString:cellLocal.service] && ![package isEqualToString:cellLocal.package] && [loai_goi isEqualToString:cellLocal.loai_goi]){
            [cellLocal.sudung setOn:NO animated:YES];
        }
     }
}

"Data" array was loaded in method loadData (not important here so I don't include it).

In UITableViewCell (class name: DichVu2TableViewCell), I set event Value Change of Switch so that each time a Switch change value (ON for example), all other cell's switch which have the same value "service" and "loai_goi" will be set OFF.

DanhsachTableViewController *tableview = [[DanhsachTableViewController alloc] init];
    tableview.tableView.delegate = (DanhsachTableViewController *)self.superview.superview;
[tableview changeCellState:_service package:_package loaigoi:_loai_goi];

But when I call, the array "data" of above tableview have 0 object so nothing happened.

Is there any way to do that?

Hi Oyeoj, Thanks for your help.

I have a little problem when followed your guide. There are some error in xcode when I use extract your code so I have to customize. But the program still has error when running. Would you please help me review my code. Thanks in advance.

DichVu2TableViewCell.h

@class DichVu2TableViewCell;
//Change : NSObject to <NSObject> because XCode 6.3 has error.
@protocol DichVu2TableViewCellDelegate <NSObject>

-(void)changeCell:(DichVu2TableViewCell *)sender state:(NSString *)service package:(NSString *)package loaigoi:(NSString *)loai_goi;

@end

@interface DichVu2TableViewCell : UITableViewCell

@property (weak) id <DichVu2TableViewCellDelegate> delegate;

@end

DichVu2TableViewCell.m

@implementation DichVu2TableViewCell
….
- (void)someSwitchingEvent
{
    [self.delegate changeCell:self state:_service package:_package loaigoi:_loai_goi];
}
@end

DanhsachTableViewController.h

@interface DanhsachTableViewController : UITableViewController

@property (strong,nonatomic) NSString *loaitb;
@property (strong,nonatomic) NSString *type;
@property (strong,nonatomic) NSString *name;
@property NSMutableArray *pre_inuse_;
@property NSMutableArray *data_inuse_;
@property NSMutableArray *vas_inuse_;
@end

DanhsachTableViewController.m

#import "DichVu2TableViewCell.h"
//Change <DichVu2TableViewCellDelegate> to (DichVu2TableViewCellDelegate) because XCode 6.3 has error.
@interface DanhsachTableViewController (DichVu2TableViewCellDelegate)
@property (nonatomic) NSIndexPath *forUpdateIndexPath;
@end

@implementation DanhsachTableViewController{
    NSMutableArray *data;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DichVu2TableViewCell *cell = (DichVu2TableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"dscell"];
    NSDictionary *dataCell =  data[indexPath.row];
    cell.service =  dataCell[@"service"];
    cell.package =  dataCell[@"package"];
    cell.loai_goi = dataCell[@"loai_goi"];
    cell.kieu_goi = dataCell[@"kieu_goi"];

    [cell.sudung setOn:NO animated:YES];
    cell.delegate = self;
//Change cellLocal —> cell because there are no cellLocal avaiable. And Program error when run to this row.
    [cell.sudung setOn:(self.forUpdateIndexPath == indexPath) animated:YES];

    return cell;
}

-(void)changeCell:(DichVu2TableViewCell *)sender state:(NSString *)service package:(NSString *)package loaigoi:(NSString *)loai_goi
{
//Add cellLocal —> cell because there are no cellLocal avaiable
    DichVu2TableViewCell *cellLocal = (DichVu2TableViewCell *)[self.tableView cellForRowAtIndexPath:self.forUpdateIndexPath];
    if ([service isEqualToString:cellLocal.service] && ![package isEqualToString:cellLocal.package] && [loai_goi isEqualToString:cellLocal.loai_goi]){
        // get the indexPath of the cell
        self.forUpdateIndexPath =  [self.tableView indexPathForCell:sender];
        // update the date source
        NSMutableDictionary *dataCell =  [data[self.forUpdateIndexPath.row] mutableCopy];
        [dataCell setObject:service forKey:@"service"];
        [dataCell setObject:package forKey:@"package"];
        [dataCell setObject:loai_goi forKey:@"loai_goi"];
        // you dont need the for-statement just reload the table
        [self.tableView reloadData];
        // then update the switch inside `- cellForRowAtIndexPath`
    }

}

iOS touch(es) blocking issue

I am encoutering a strange issue with an iOS application that I'm currently working on, issue related to touches.

For exemplification, the layout of the app looks something like this (its quite basic, nothing fancy, just some buttons and a touch area):

Application layout

A is the touch area (its a CONTAINER which has a View inside, view that displays an image , image that is affected by the way im touching the area).

B is a simple iOS button (the one you create by default with XCODE , with just a changed background color and size (width/height).

Now , the issue: it only happens some times, I could not yet figure out why and when, but I can reproduce it sometimes. Basically, when clicking B , touches on A (with a finger from the left hand) behave strange: i am receiving the touchesMoved event, but the touch position is the position of the touch on B, hence the movement of the image in A does not happen, and when it happens (after removing the right hand finger from B), the movement behaves as if the touch was at the B position.

Here is part of the code , the part that handles touches, in the ViewController attached to the A view. I have removed some of the code that I dont think its related to my issue, to keep things cleaner.

-(void)touchesBegan:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{

    NSLog(@"A View touched : %d", [touches count]);
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView: _theAView];
    NSLog(@"Touch at %f %f", touchLocation.x, touchLocation.y);
    initialTouchX = touchLocation.x;
    initialTouchY = touchLocation.y;    


}

-(void)touchesMoved:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{

    /*
    some code was here handling time, to only handle moving every X milliseconds
    */
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:theAView];


    /*
    code handling the display of the image , removed
    */
    initialTouchX = touchLocation.x;
    initialTouchY = touchLocation.y;

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {

}

As for the code of the B button, its just a basic IBAction, which calls a function with a parameter:

- (IBAction)btnDown:(id)sender {
    //call some function here 
}

Two things to note:

1) in the code above, "theAView" reffers to the view in the A area. 2) the 1st part of code (the one with the touches) resides in a different ViewController; the 2nd part of the code, for the button, resides in the default ViewController file that XCODE creates when creating a project.

I also tried enabling multitouch on both the A view and the B button, but the problem is still there.

Any help is appreciated.

Thanks in advance.

Gamecenter new match creation with specific opponent

I'm creating a turn-based game using gamecenter. It is a one to one game so every game has two participants.

When a game is finished, a gameover screen appears and either of the participants can press "rematch" to start a new game with the same opponent.

The code I use when the button is pressed is (simplified) this:

let request = GKMatchRequest()
        request.maxPlayers = 2
        request.minPlayers = 2
        request.recipients = [opponent]

GKTurnBasedMatch.findMatchForRequest(request, withCompletionHandler: {
            match, error in
            if error != nil {
                println("FIND MATCH REQUEST ERROR:\(error.localizedDescription)")
            } else {
                println("Match Found")}})

Now, my question is this. When I rematch a game where the opponent is a friend of mine in gamecenter everything seems to work fine. However, if I rematch a game where the opponent is not a friend of mine in gamecenter I get the following error:

The requested operation could not be completed because the player is invalid.

However, when I print the opponent player (GKPlayer) I get the following (which seems to be fine and not invalid as the error suggests):

(playerID:g:58D9E388A2CD0DEFC795DC9035E7D22A alias:TestBoomar_1 name:‎“‪TestBoomar_1‬” status:(null))

So, my question is this: Do GKMatchRequest recipients have to be the players friends in order for those recipients to be valid? Shouldn't recipients be able to be any players in Gamecenter, not dependent on whether they are friends of the game creator?

Any input is appreciated, Thanks!

How to recognise a song by listening using Echonest for iOS?

I want to implement a functionality similar to the one integrated in Shazam app. I want my app by pressing to a button to "listen" for a song and after some time to "guess" the song or give some predictions using Echonest api for iOS. I was searching the web and so far I've learned the I need to send the fingerprint to the Echonest server and give me response with the song info. But somewhere I've read that that functionality will be no more available. Also tried to upload the whole mp3 file to their server and the response is always an empty one. Does anyone has experience with this issue and tell me where I'm wrong? I've used echoprint but no success.

MySQL server and iOS app

I am running a site right now with a quite big MySQL database. Now, I want to create an app. I will need to use obviously a database de to the fact my data are already there.

Thus,

1) Should I keep using the MySQL server and my iOS app will connect to this MySQL serve for getting data?

2) is there any problem if I use the MySQL server ? Security issues maybe?

3) if I have to change the MySQL server, what database infrastructure I need to build and work with?

I am totally newbie on iOS apps. And now I planning to face any issues my iOS app will have.

Fix Fatal iOS crash

I am AdHoc testing an iOS app on iPad mini and iPhone 4. The app worked fine 48 hours ago on both platforms but is now fatally crashing/freezing when I test on iPhone 4. The app lets you login to an apache server using php/json, take pics using the iOS camera, then upload the pics to a vertical UIScrollView where the pics are viewed as jpeg thumbs. From there you can tap a thumb and view it full screen.The app works perfectly on iPad but not on iPhone 4. The app crashes (either freezes or goes back to the home screen) when I tap a photo jpeg thumb in the UIScrollView to view it full screen. (this works fine on iPad testing).

All i want to do right now is view a photo fullscreen on iPhone 4 but the app keeps fatally freezing. The second I tap a photo on iPhone, the app freezes and the compiler highlights the following line of code in the application.

[api commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"stream", @"command", IdPhoto,@"IdPhoto", nil] onCompletion:^(NSDictionary *json) { 

//after this line of code is a 
Thread 1. EXC_BAD_ACCESS(code=1,address=ox28)

This is also a line of code the compiler points to after the freeze/crash. (It high lights the above live half the time and this line other times with the same 'Thread 1' alert.

if([value isKindOfClass:[NSDictionary class]]) {