#StackBounty: #ios #objective-c #crash-analytics How to fetch iOS crash logs programmatically?

Bounty: 50

I am looking to retrieve the crash logs in iPhone programmatically.
Under iOS 10 and above, the list of logs can be found here :

Settings --> Privacy -->Analytics --> Analytics Data-->logfiles.json

Is it possible to access the log files programmatically.
I am basically looking to get all the files that are found in the data section.Not just the files related to my app.

Note : I am not looking here for Appstore approval.


Get this bounty!!!

#StackBounty: #ios #swift #uitableview delete row UITableView index issue

Bounty: 50

I’m using the code below to delete a row in my tableview. First I delete the object from my array and then from the tableview using this code:

let i = IndexPath(item: rowNum, section: 0)
myArray.remove(at: rowNum)
myTableView.deleteRows(at: [i], with: UITableViewRowAnimation.left)

However, if I delete another row right after, not the row I wanted to be deleted gets deleted. The issue is, even though I deleted the first item in the tableview (e.g. index 0), clicking on the new first row returns index 1… which is wrong, and deletes the second row. After deleting the first row the new row at the top should have an index of 0.

I can solve this problem by doing:

mTableView.reloadData()

but this seems wrong… I shouldn’t have to reload all the data again.

What else can I do?

EDIT: I have a custom button in my tableviewcell I am pressing to delete the row – not swiping.


Get this bounty!!!

#StackBounty: #ios #swift #swift3 #avaudioplayer #video-capture Record Video and play audio at same time ios

Bounty: 50

I want to record video and play audio simultaneously. when start recording video, preloaded audio start play and when stop video recording, audio also stops playing.

I tried to record Video by using third party library “SwiftyCam” (https://github.com/Awalz/SwiftyCam) and start playing audio in delegate method when start writes video recording file.

main ViewCOntroller code is below :

override func viewDidAppear(_ animated: Bool) {
 super.viewDidAppear(animated)
 var temp = Data()
 let audioPath = Bundle.main.path(forResource: "ab1-FAST", ofType: "mp3")
        temp = FileManager.default.contents(atPath: (audioPath)!)!
     do {
            player = try  AVAudioPlayer(data: temp)
        }
        catch let error {

            print(error)
        }

        self.configureAudioSession()
        player!.delegate = self
        self.player!.prepareToPlay()
}

    // MARK: -
    // MARK: - SwiftyCamViewControllerDelegate method

func swiftyCam(_ swiftyCam: SwiftyCamViewController, didBeginRecordingVideo camera: SwiftyCamViewController.CameraSelection) {
  self.player?.play()
}

func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFinishRecordingVideo camera: SwiftyCamViewController.CameraSelection) 
{
        if self.player != nil{
            if (self.player?.isPlaying)! {
                self.player?.stop()
            }
        }
}


@IBAction func btnStartStopClick(_ sender: UIButton) {

        sender.isSelected = !sender.isSelected
        if sender.isSelected{

            DispatchQueue.main.async {
                self.objVideoRecorderVC.startVideoRecording()
            }
        }else{
             self.objVideoRecorderVC.stopVideoRecording()

        }
  }

swiftycam Library :

/**

    Begin recording video of current session

    SwiftyCamViewControllerDelegate function SwiftyCamDidBeginRecordingVideo() will be called

    */
public func startVideoRecording() {
        guard let movieFileOutput = self.movieFileOutput else {
            return
        }

        if currentCamera == .rear && flashEnabled == true {
            enableFlash()
        }

        if currentCamera == .front && flashEnabled == true {
            flashView = UIView(frame: view.frame)
            flashView?.backgroundColor = UIColor.white
            flashView?.alpha = 0.85
            previewLayer.addSubview(flashView!)
        }

        sessionQueue.async { [unowned self] in
            if !movieFileOutput.isRecording {
                if UIDevice.current.isMultitaskingSupported {
                    self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
                }

                // Update the orientation on the movie file output video connection before starting recording.
                let movieFileOutputConnection = self.movieFileOutput?.connection(withMediaType: AVMediaTypeVideo)


                //flip video output if front facing camera is selected
                if self.currentCamera == .front {
                    movieFileOutputConnection?.isVideoMirrored = true
                }

                movieFileOutputConnection?.videoOrientation = self.getVideoOrientation()

                // Start recording to a temporary file.
                let outputFileName = UUID().uuidString
                let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent((outputFileName as NSString).appendingPathExtension("mov")!)


                movieFileOutput.startRecording(toOutputFileURL: URL(fileURLWithPath: outputFilePath), recordingDelegate: self)
                self.isVideoRecording = true
    DispatchQueue.main.async {
                    self.cameraDelegate?.swiftyCam(self, didBeginRecordingVideo: self.currentCamera)
                }
            }
            else {
                movieFileOutput.stopRecording()
            }
        }
    }

issue: sometimes getting a delay in start playing audio in a microsecond.
when audio start play and sound record in video recording some time sync proper and some time delay in sound.

I check it with merge audio with original audio and there is some delay as shown below image. the issue is not always but random delay and not sync.enter image description here

enter image description here
are any solutions?
how to do record video and play audio at the same time(on single button click) start and no delay and no sync issue?
is any other way?

for play audio used: AVAudioPlayer

for record video used : Swiftycam (AVCaptureSession)


Get this bounty!!!

#StackBounty: #ios #viewcontroller #uitapgesturerecognizer IOS: first tap not working just after loading view

Bounty: 50

I have noted recently that each of my app view has one particular bug/behaviour: if user taps too fast on a UI component when the view appears, the tap is simply ignored. If the user wait a bit before tapping, the tap works.

Storyboard is used for the storyboard, tap gesture recognisers are on UIImageview and using IOS 10.2.

Through different forums i have read about the following options:

  • nest the call of “present view controllers” in main thread
  • Call CFRunLoopWakeup before presentviewcontroller
  • Add programatically the TapGesturerecognizer
  • change the states of “delays touches end” and “delays touches began”

All above have been unsuccessful.

Anyone would have met similar issues with the first tap just after the view load?

Stephane


Get this bounty!!!

#StackBounty: #ios #swift2 #uipageviewcontroller #addsubview subview scroll is not working SWIFT

Bounty: 50

Goal: to make a viewcontroller have multiple pages and can be swapped through a segmented controller, pages content are scrollable vertically

details:

  • I made a pagviewcontroller and embedded it as a subview to main viewcontroller
    //add pageviewcontroller as subview to viewcontroller
    if let vc = storyboard?.instantiateViewControllerWithIdentifier("ProfileEditController"){
    
        self.addChildViewController(vc)
        self.view.addSubview(vc.view)
    
        EditTabs = vc as! UIPageViewController
        EditTabs.dataSource = self
        EditTabs.delegate = self
    
        //define First page
        EditTabs.setViewControllers([pagesAtIndexPath(0)!], direction:.Forward, animated: true, completion: nil)
        EditTabs.didMoveToParentViewController(self)
    
        //bring segmented view buttons to front of pageViews
        self.view.bringSubviewToFront(self.topTabs)
    }
    
  • I called pageViewController functions, and I am adding pages through restoration Identifiers

  • I managed segmented view controller by getting pageindex and setting viewcontroller like this:
    EditTabs.setViewControllers([pagesAtIndexPath(0)!], direction:.Reverse, animated: true, completion: nil)
    
  • in story board the sub pages has scroll view inside to hold the content

  • I tested subpages scroll view by calling it through segue and its working fine

Case:

  • everything work fine Only scroll view of subpages are not working at all

How to solve this issue?
your guidelines will be much appreciated

Thanks,


Get this bounty!!!

#StackBounty: #ios #xcode #swift3 #mpmediaplayercontroller Quitting app causes error "Message from debugger: Terminated due to sig…

Bounty: 50

I’m writing a basic music player app but having some problems when it comes to handling the app state transitions.

I’m using Swift 3 and MPMusicPlayerController.systemMusicPlayer()

The goal is this:

1) Keep music playing when user taps the Home button and app enters bg (works)

2) Stop the player ( myMP.stop() ) if the user the quits the app (works sometimes, throws error other times)

I traced the flows using print statements based on possible actions and got this:

enter image description here

Flow 2 is what I would expect, but Flow 1 throws an error
when the app is closed – I would expect “will terminate” here.

EDIT: The main issue is that when exiting the app using Flow 1, “will terminate” is never called – therefore “myMP.stop()” is never called and the player continues to play after the app has exited.

There is a distinct difference in behavior if you click Home once (Flow 1) or double (Flow 2) while the app is active.

Why do I get two different responses from what should be the same actions?

EDIT:
Most importantly, how do I stop the MediaPlayer for Flow 1 if it never gets to “will terminate” ?


Get this bounty!!!

#StackBounty: #c# #ios #iphone #uitableview #xamarin Custom UITableViewCell: First Row Has No Content

Bounty: 50

I am trying to create a two-level UITableView implementation for a comment and reply panel. The first level contains all top-level comments and if there are replies to that comment, there will be an indicator. When you tap on a top-level comment cell, the panel will animate a new UITableView into view. The first cell is the comment the user tapped on and below that is a cell for each reply to that comment.

I accomplish by using two different UITableViews and two different UITableViewSources (but they share the same base class). When the user taps on a top-level comment, the controller that manages the tables (CommentPanelViewController) animates the old view (top-level comments) out of sight and the new view (replies) into sight.

The Issue:

When I tap on the top-level comment, nothing but it’s indicator shows up. All of the other replies display fine but the top-level comment has no text, no author and no timestamp on it.

To keep things concise and easy to follow, I will post just the necessary code. The top-level comments view works perfectly, only the reply view is buggy so we will start there:

CommentSource – the base table source

public abstract class CommentSource : UITableViewSource
{
    protected List<Comment> _data;

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {
        var comment = _data[indexPath.Row];
        var cell = tableView.DequeueReusableCell(CellId)
            as CommentCell ?? new CommentCell(new NSString("CellId"), CommentLineCount,
            comment.Replies != null && comment.Replies.Count > 0);

        cell.SelectionStyle = UITableViewCellSelectionStyle.None;
        cell.LayoutMargins = UIEdgeInsets.Zero;
        cell.SeparatorInset = UIEdgeInsets.Zero;
        cell.SetNeedsUpdateConstraints();
        cell.UpdateConstraintsIfNeeded();
        cell.UpdateCell(comment);
        cell.DrawIndicator(comment);

        DrawAccessories(comment, cell);

        return cell;
    }

    protected virtual void DrawAccessories(Comment comment, CommentCell cell) { }

    protected abstract int CommentLineCount { get; }

    protected abstract string CellId { get; }

    public override nint RowsInSection(UITableView tableview, nint section) => _data?.Count ?? 0;

    public void UpdateData(IEnumerable<Comment> comments)
    {
        _data = OrderComments(comments);
    }

    private static List<Comment> OrderComments(IEnumerable<Comment> comments) =>
        comments?.OrderBy(x => x.CreatedDateTime).ToList();
}

CommentViewSource – the source for top-level comments

public class CommentViewSource : CommentSource
{
    protected override int CommentLineCount => 3;
    protected override string CellId => "CommentCell";

    public Action<Comment, bool> CommentSelected { get; set; }

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        var commentCell = tableView.CellAt(indexPath) as CommentCell;
        CommentSelected(_data[indexPath.Row], commentCell != null && commentCell.IsEllipsed);
    }

    protected override void DrawAccessories(Comment comment, CommentCell cell)
    {
        base.DrawAccessories(comment, cell);
        if (comment.Replies.Count > 0)
        {
            cell.DrawReplyCountIndicator(comment);
        }
    }
}

ReplyViewSource – source for the replies

public class ReplyViewSource : CommentSource
{
    protected override int CommentLineCount => 0;

    protected override string CellId => "ReplyCell";
}

So when a top-level comment is selected, CommentViewSource.RowSelected is called which calls CommentViewSource.CommentSelected which is handled:

CommentPanelViewController.Constructor:

public CommentPanelViewController(CommentViewSource commentSource,
    CommentSource replySource, Action dismissHandler)
{
    _isReplyVisible = false;
    _commentSource = commentSource;
    _commentSource.CommentSelected += (comment, isEllipsed) =>
    {
        if (comment.Replies.Count <= 0 && !isEllipsed) { return; }

        var replies = new List<Comment>(comment.Replies);
        if (!replies.Contains(comment))
        {
            replies.Insert(0, comment);
        }
        _replySource.UpdateData(replies);
        _replyView.Table.ReloadData();
        AnimateReplyView(true);
    };
    _replySource = replySource;

    ..........
 }

And now for the big one, the custom UITableViewCell. This class is used for both the replies and the top-level comments:

CommentCell

public sealed class CommentCell : UITableViewCell
{
    private const string CustomCommentCss =
        "<style>*{{font-family:{0};font-size:{1};color:{2};}}span{{font-weight:600;}}</style>";
    private readonly bool _hasReplies;
    private readonly UILabel _creatorLabel;
    private readonly UILabel _commentLabel;
    private readonly UILabel _dateLabel;
    private readonly UIFont _font;
    private bool _didUpdateConstraints;
    private UIView _indicator;
    private ReplyCountIndicatorView _replyCountIndicator;

    public CommentCell(NSString cellId, int numberOfLines, bool hasReplies) :
        base(UITableViewCellStyle.Default, cellId)
    {
        _hasReplies = hasReplies;
        _didUpdateConstraints = false;
        SelectionStyle = UITableViewCellSelectionStyle.None;

        var textColor = Globals.ColorDark;

        _font = UIFont.FromName(Globals.FontSanFranLight, Globals.FontSizeBody);
        _creatorLabel = new UILabel
        {
            Font = UIFont.FromName(Globals.FontSanFranSemiBold, Globals.FontSizeBody),
            Lines = 1,
            LineBreakMode = UILineBreakMode.TailTruncation,
            TextColor = textColor
        };
        _commentLabel = new UILabel
        {
            Font = _font,
            Lines = numberOfLines,
            LineBreakMode = UILineBreakMode.TailTruncation,
            TextColor = textColor
        };
        _dateLabel = new UILabel
        {
            Font = UIFont.FromName(Globals.FontSanFranLight, Globals.FontSizeSmall),
            TextColor = Globals.ColorDisabled
        };

        ContentView.AddSubviews(_creatorLabel, _commentLabel, _dateLabel);
    }

    public bool IsEllipsed => _commentLabel.Text.StringSize(
        _commentLabel.Font).Width > 3 * _commentLabel.Bounds.Size.Width;

    public override void UpdateConstraints()
    {
        base.UpdateConstraints();
        _creatorLabel.SetContentCompressionResistancePriority(1000, UILayoutConstraintAxis.Vertical);
        _commentLabel.SetContentCompressionResistancePriority(1000, UILayoutConstraintAxis.Vertical);
        _dateLabel.SetContentCompressionResistancePriority(1000, UILayoutConstraintAxis.Vertical);
        _replyCountIndicator?.SetContentCompressionResistancePriority(1000, UILayoutConstraintAxis.Vertical);

        if (_didUpdateConstraints || (_replyCountIndicator == null && _hasReplies)) { return; }

        var leftMargin = AnnotationIndicator.Size.Width + 2 * Globals.MarginGrid;

        if (_replyCountIndicator != null && _hasReplies)
        {
            ContentView.ConstrainLayout(() =>
                _creatorLabel.Frame.Top == ContentView.Frame.Top + Globals.MarginGrid &&
                _creatorLabel.Frame.Left == ContentView.Frame.Left + leftMargin &&
                _creatorLabel.Frame.Right == ContentView.Frame.Right - Globals.MarginGrid &&

                _commentLabel.Frame.Top == _creatorLabel.Frame.Bottom + Globals.MarginGrid / 4 &&
                _commentLabel.Frame.Left == _creatorLabel.Frame.Left &&
                _commentLabel.Frame.Right == _creatorLabel.Frame.Right &&

                _dateLabel.Frame.Top == _commentLabel.Frame.Bottom + Globals.MarginGrid / 4 &&
                _dateLabel.Frame.Left == _creatorLabel.Frame.Left &&
                _dateLabel.Frame.Right == _creatorLabel.Frame.Right &&

                _replyCountIndicator.Frame.Top == _dateLabel.Frame.Bottom + Globals.MarginGrid &&
                _replyCountIndicator.Frame.Left == _dateLabel.Frame.Left &&
                _replyCountIndicator.Frame.Width == Globals.SmallToolbarItemSize &&
                _replyCountIndicator.Frame.Height == Globals.SmallToolbarItemSize &&
                _replyCountIndicator.Frame.Bottom == ContentView.Frame.Bottom - Globals.MarginGrid);   
        }
        else
        {
            ContentView.ConstrainLayout(() =>
                _creatorLabel.Frame.Top == ContentView.Frame.Top + Globals.MarginGrid &&
                _creatorLabel.Frame.Left == ContentView.Frame.Left + leftMargin &&
                _creatorLabel.Frame.Right == ContentView.Frame.Right - Globals.MarginGrid &&

                _commentLabel.Frame.Top == _creatorLabel.Frame.Bottom + Globals.MarginGrid / 4 &&
                _commentLabel.Frame.Left == _creatorLabel.Frame.Left &&
                _commentLabel.Frame.Right == _creatorLabel.Frame.Right &&

                _dateLabel.Frame.Top == _commentLabel.Frame.Bottom + Globals.MarginGrid / 4 &&
                _dateLabel.Frame.Left == _creatorLabel.Frame.Left &&
                _dateLabel.Frame.Right == _creatorLabel.Frame.Right &&
                _dateLabel.Frame.Bottom == ContentView.Frame.Bottom - Globals.MarginGrid);
        }

        _didUpdateConstraints = true;
    }

    public void UpdateCell(Comment comment)
    {
        // update the comment author
        _creatorLabel.Text = string.IsNullOrWhiteSpace(comment.CreatedByUser.FirstName) &&
            string.IsNullOrWhiteSpace(comment.CreatedByUser.LastName) ?
                comment.CreatedByUser.Email :
                $"{comment.CreatedByUser.FirstName} {comment.CreatedByUser.LastName}";

        // update the text
        var attr = new NSAttributedStringDocumentAttributes { DocumentType = NSDocumentType.HTML,  };
        var nsError = new NSError();

        var text = comment.Text.Insert(0, string.Format(CustomCommentCss,
            _font.FontDescriptor.Name, _font.PointSize,
            ColorConverter.ConvertToHex(_commentLabel.TextColor)));
        var mutableString = new NSMutableAttributedString(new NSAttributedString(
            text, attr, ref nsError));
        var mutableParagraph = new NSMutableParagraphStyle
        {
            Alignment = UITextAlignment.Left,
            LineBreakMode = UILineBreakMode.TailTruncation
        };
        mutableString.AddAttribute(UIStringAttributeKey.ParagraphStyle, mutableParagraph,
            new NSRange(0, mutableString.Length));
        mutableString.AddAttribute(UIStringAttributeKey.StrokeColor, Globals.ColorDark,
            new NSRange(0, mutableString.Length));
        _commentLabel.AttributedText = mutableString;

        // update the timestamp
        var localTime = TimeZone.CurrentTimeZone.ToLocalTime(
            comment.LastModifiedDateTime).ToString("g");
        _dateLabel.Text = comment.LastModifiedDateTime == comment.CreatedDateTime ? 
            localTime : $"Modified {localTime}";
    }

    public void DrawIndicator(Comment comment)
    {
        // if we've already drawn the indicator and 
        // the comment has no annotation associated with it
        _indicator?.RemoveFromSuperview();

        // if the comment havs an annotation associated with it,
        // draw the annotation indicator
        if (comment.Annotation != null)
        {
            _indicator = new AnnotationIndicator
            {
                Location = new CGPoint(Globals.MarginGrid, Globals.MarginGrid),
                Number = comment.Annotation.AnnotationNumber,
                FillColor = Color.FromHex(comment.Annotation.FillColorValue).ToUIColor(),
                TextColor = Color.FromHex(comment.Annotation.TextColorValue).ToUIColor()
            };
            AddSubview(_indicator);
        }

        // otherwise, draw the general comment indicator
        else
        {
            var size = comment.IsReply ? ReplyIndicator.DotSize : AnnotationIndicator.Size;
            _indicator = comment.IsReply ?
                new ReplyIndicator
                {
                    Frame = new CGRect(Globals.MarginGrid + size.Width / 2,
                        Globals.MarginGrid + size.Height / 2, ReplyIndicator.DotSize.Width,
                        ReplyIndicator.DotSize.Height)
                } as UIView :
                new UIImageView
                {
                    Image = UIImage.FromFile("general_annotation_indicator.png"),
                    Frame = new CGRect(Globals.MarginGrid, Globals.MarginGrid, size.Width, size.Height)
                };
            AddSubview(_indicator);
        }
    }

    public void DrawReplyCountIndicator(Comment comment)
    {
        if (_replyCountIndicator != null) { return; }

        _replyCountIndicator = new ReplyCountIndicatorView(comment.Replies.Count);
        ContentView.AddSubview(_replyCountIndicator);

        _didUpdateConstraints = false;
        UpdateConstraints();
    }
}

If anyone would like to see more code, feel free to ask.

Thanks in advanced for the assistance!

Here are some screenshots of the problem:

Top-level comments work

Replies, not so much


Get this bounty!!!

#StackBounty: #ios #swift #video #avassetexportsession #avmutablecomposition AVAssetExportSession does not honour videocomposition inst…

Bounty: 50

I am trying to apply AVMutableVideoCompositionLayerInstruction on an AVMutableComposition for a video. The problem is it does not honour the instruction when the video is saved using AVAssetExportSession. The weird part is, the same composition works with AVPlayer (AVPlayer honours the instruction).

Here’s the code:

        let path = Bundle.main.path(forResource: "flame", ofType: "mp4")
        let url = NSURL(fileURLWithPath: path!)
        let asset = AVAsset(url: url as URL)

        let mutableComposition = AVMutableComposition()

        let type = AVMediaTypeVideo
        let prefTrackID = kCMPersistentTrackID_Invalid

        let sourceVideoAssetTrack: AVAssetTrack = asset.tracks(withMediaType: type).first!
        let sourceAudioAssetTrack: AVAssetTrack = asset.tracks(withMediaType: AVMediaTypeAudio).first!

        let videoCompositionTrack1 = mutableComposition.addMutableTrack(withMediaType: type, preferredTrackID: prefTrackID)


        do {
            let range = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60,600))
            try videoCompositionTrack1.insertTimeRange(range, of: sourceVideoAssetTrack, at: kCMTimeZero)
        }catch { print(error) }

        let firstTransform = videoCompositionTrack1.preferredTransform;

        let fromLayer = AVMutableVideoCompositionLayerInstruction(assetTrack: videoCompositionTrack1)
        fromLayer.setTransform(firstTransform, at: kCMTimeZero)
        fromLayer.setCropRectangle(CGRect.init(x: 5, y: 5, width: 200, height: 200), at: kCMTimeZero)

        let instruction = AVMutableVideoCompositionInstruction()
        instruction.layerInstructions = [fromLayer]
        instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60,600))

        videoComposition = AVMutableVideoComposition()
        videoComposition!.instructions = [instruction]
        videoComposition!.renderSize = CGSize.init(width: 300, height: 300)
        videoComposition!.frameDuration = CMTimeMake(1, 30)


        if(true){ // just to switch between the saving and playing modes
            var exportPath: NSString = NSTemporaryDirectory().appendingFormat("/video.mov")
            var exportUrl: NSURL = NSURL.fileURL(withPath: exportPath as String) as NSURL

            var exporter = AVAssetExportSession(asset: mutableComposition, presetName: AVAssetExportPresetMediumQuality)!
            exporter.outputURL = exportUrl as URL
            exporter.videoComposition = videoComposition!

            exporter.outputFileType = AVFileTypeMPEG4
            exporter.shouldOptimizeForNetworkUse = true
            exporter.canPerformMultiplePassesOverSourceMediaData = true

            exporter.exportAsynchronously(completionHandler: {
                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: exportUrl as URL)
                }) { completed, error in
                    if completed {
                        print("Video is saved!")
                    }
                }
            })
        }
        else{
            let playerItem = AVPlayerItem(asset: mutableComposition)
            playerItem.videoComposition = videoComposition!
            player = AVPlayer(playerItem: playerItem)
            playerLayer = AVPlayerLayer(player: player)
            playerLayer.frame = self.view.frame
            self.view.layer.addSublayer(playerLayer)
            player.play()
        }

AVPlayer honours cropRectangle instruction

AVPlayer honours cropRectangle instruction as seen above

Saved video is same as the original video

Saved video is same as the original video.

I am building this on iOS 9. What am I doing wrong?


Get this bounty!!!

#StackBounty: #ios #concurrency #ews #nsurlsession NSURLSession multiple concurrent requests refused by Exchange server

Bounty: 50

I have replaced my NSURLConnection code with NSURLSession to fetch data with EWS Exchange server. My app makes multiple concurrent API calls. It was working fine but now, when I am using NSURLSession some of my API calls get correct response and some gets the error from exchange server as follows:

{
"s:Envelope" =     {
    "s:Body" =         {
        "m:GetItemResponse" =             {
            "m:ResponseMessages" =                 {
                "m:GetItemResponseMessage" =                     {
                    ResponseClass = Error;
                    "m:DescriptiveLinkKey" =                         {
                        text = 0;
                    };
                    "m:Items" =                         {
                    };
                    "m:MessageText" =                         {
                        text = "An internal server error occurred. The operation failed., Cannot open mailbox /o=First Organization/ou=Exchange Administrative Group(FYDIBOHF23SPDLT)/cn=Recipients/cn=00037FFEE6F0D3D2.";
                    };
                    "m:MessageXml" =                         {
                        "t:Value" =                             (
                                                            {
                                Name = InnerErrorMessageText;
                                text = "Too many concurrent connections opened.";
                            },
                                                            {
                                Name = InnerErrorResponseCode;
                                text = ErrorTooManyObjectsOpened;
                            },
                                                            {
                                Name = InnerErrorDescriptiveLinkKey;
                                text = 0;
                            }
                        );
                    };
                    "m:ResponseCode" =                         {
                        text = ErrorInternalServerError;
                    };
                };
            };
            "xmlns:m" = "http://schemas.microsoft.com/exchange/services/2006/messages";
            "xmlns:t" = "http://schemas.microsoft.com/exchange/services/2006/types";
        };
        "xmlns:xsd" = "http://www.w3.org/2001/XMLSchema";
        "xmlns:xsi" = "http://www.w3.org/2001/XMLSchema-instance";
    };
    "s:Header" =         {
        "h:ServerVersionInfo" =             {
            MajorBuildNumber = 1034;
            MajorVersion = 15;
            MinorBuildNumber = 11;
            MinorVersion = 1;
            xmlns = "http://schemas.microsoft.com/exchange/services/2006/types";
            "xmlns:h" = "http://schemas.microsoft.com/exchange/services/2006/types";
            "xmlns:xsd" = "http://www.w3.org/2001/XMLSchema";
            "xmlns:xsi" = "http://www.w3.org/2001/XMLSchema-instance";
        };
    };
    "xmlns:s" = "http://schemas.xmlsoap.org/soap/envelope/";
};

Apparently the problem is too many connections at same time.

My code flow is:

My HTTPRequest.m has a method

- (void)fetchData
{
    dispatch_async(dispatch_get_main_queue(), ^{

        sessionAlive = sessionAlive + 1;

        NSLog(@"sessionCount: %ld", (long)sessionAlive);

        NSURLSessionConfiguration *defaultConfiguration = [NSURLSessionConfiguration ephemeralSessionConfiguration];

        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfiguration
                                                                     delegate:self
                                                               delegateQueue:nil];

        NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:request];

        [dataTask resume];
    });
}

// Some NSURLSession delegates methods here

-(void)URLSession:(NSURLSession *)session
     dataTask:(NSURLSessionDataTask *)dataTask
   didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}

-(void)URLSession:(NSURLSession *)session
             task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
    if (error)
    {
        self.failureBlock ? self.failureBlock(error) : nil;
    }
    else
    {
        NSData *data;

        if (self.data)
        {
            data = [NSData dataWithData:self.data];
        }

        self.successBlock ? self.successBlock(self.redirectLocation, data) : nil;
    }

    [session finishTasksAndInvalidate]; // We must release the session, else it holds strong referance for it's delegate (in our case EWSHTTPRequest).
                                        // And it wont allow the delegate object to free -> cause memory leak
}

And I am downloading emails concurrently something like this:

dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

dispatch_async(backgroundQueue, ^{

foreach (NSString *emailId in emalilIDArray)
    {
     HTTPRequest *request = [HTTPRequest alloc] init];
      [request fetchData];
    }
});

I think my problem is that I am making session on each call and but I don’t know see other way.

If I cant use a shared-instance session, as I need to associate session’s delegate with each HTTPRequest object to handle the response.

Any suggestion or better approach ?


Get this bounty!!!

#StackBounty: #html #ios #css z-index treated differently on iOS when setting -webkit-overflow-scrolling: touch

Bounty: 50

I’m seeing some interesting z-index behaviour on iOS.

My sample code can be viewed here: https://jsfiddle.net/59mo8s16/4/

I need the #sidebar to be displayed in front of the #slide-in-tip. This is the case when viewed on Chrome (PC and Android) and Firefox (PC). However, on iOS Safari and Chrome, #slide-in-tip appears in front of #sidebar.

I’ve realised that removing -webkit-overflow-scrolling: touch from the CSS makes it appear as intended across all platforms/browsers. However, I need this in order to provide momentum scrolling for the #container div on iOS. Without it, you get that scrolling that stops as soon as you stop swiping, which provides a terrible user experience.

Any ideas on how to resolve this one? Ideally I’d like a CSS-only solution. Any significant restructure of HTML will cause me some major pain at this point. The sample is a really stripped back version of an already-complete website.

HTML:

<

div class=”snippet”>

<

div class=”snippet-code”>

html,
body {
  height: 100%;
  margin: 0;
  -webkit-overflow-scrolling: touch;
}

#top-bar {
  top: 0;
  width: 100%;
  z-index: 200;
  background-color: green;
  height: 85px;
  position: absolute;
}

#sidebar {
  float: left;
  padding: 30px;
  background-color: pink;
  position: fixed;
  width: 310px;
  left: 0px;
  z-index: 150;
  top: 85px;
  bottom: 0px;
  padding: 0;
  padding-bottom: 50px;
}

#container2 {
  min-height: 100%;
}

#main {
  padding-right: 20px;
  height: 100%;
  margin: 0;
  margin-left: 10%;
  line-height: 40px;
  text-align: right;
}

#container {
  height: 100%;
  margin: 0;
  position: absolute;
  width: 100%;
  overflow-y: scroll;
}

#container2 {
  padding-top: 75px;
}

#slide-in-tip {
  position: fixed;
  bottom: 0;
  text-align: right;
  width: 100%;
  z-index: 140;
  background-color: blue;
  height: 200px;
}
top-bar
long content - see js fiddle for actual long content
</div> </div>
slide-in-tip