Menu
  • HOME
  • TAGS

NSURL with string relative to URL returning unexpected result

ios,xcode,afnetworking-2,nsurl

You are missing a scheme. NSURL seems to interpret the localhost: part as scheme, which causes unexpected behaviour. In case of http you should try this: NSURL *url = [NSURL URLWithString:@"rooms" relativeToURL:[NSURL URLWithString:@"http://localhost:9000/"]]; ...

Make a local NSURL from an NSString containing HTML?

ios,objective-c,nsstring,nsurl

The question you are asking makes absolutely no sense. A URL is a pointer to the location of a resource online. In this context a html file. You can not make one into the other. I suggest you create a UIWebView, load the string into that, have it render and...

UIImage returns null first time, until reloaded? [duplicate]

ios,objective-c,uiimage,nsurl

The connection:didReceiveData: method is called repeatedly as the data is loaded incrementally. You probably want the connectionDidFinishLoading: method instead. By the way, you'll still likely need a connection:didReceiveData:, but rather than trying to create the image, you'll just be appending the new data to a buffer. Then in the connectionDidFinishLoading:...

NSURLConnection and NSMutableURLRequest Authentication

ios,objective-c,http,nsurl

A couple of thoughts: I'm surprised by the presence of reserved characters in __VIEWSTATE and __EVENTVALIDATION. Per the x-www-form-urlencoded spec, you should be percent escaping characters other than *, -, ., 0-9, A-Z, _ and a-z. My standard percent-escaping routine for POST values is: - (NSString *)percentEscapeString:(NSString *)string { NSString...

Saving an array of NSURL to NSUserDefaults

swift,nsuserdefaults,nsurl

when saving, save the absolute strings of the urls. when loading use NSURL(URLString:) to make the strings into urls again import UIKit class ViewController: UIViewController { var urlsArray : [NSURL]? func load () { var urls : [NSURL] = [] let stringsArray = NSUserDefaults.standardUserDefaults().objectForKey("stringsArray") as [String]? if let array =...

Convert NSData from local NSURL

ios,objective-c,cocoa-touch,nsdata,nsurl

From the error it seems as if podcastSource is an NSString when it needs to be an NSUrl if you're going to request its path. But according to the Apple Docs, dataWithContentsOfFile: accepts an NSString as the argument, so no need to convert podcastSource into an NSUrl or to request...

Can't urlencode deviceToken (Swift)

swift,ios8,nsdata,nsurl

Can you pinpoint what variable is being unwrapped and returning nil? I can't see anything that would cause that, except the URL, so your error might be an invalid URL. Remember NSURL validates the string given according to a strict syntax (RFC 2396). Try this URL (without the deviceToken) and...

iOS WebView, fixed image src name, create image (nsdata, nsbundle, nsurl) dynamically?

ios,objective-c,webview,nsurl

you may try to save image into local file and set the url of file instead of image name in web view. try the following NSData* data = UIImagePNGRepresentation(yourDynamicImage); NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDirectory = [paths objectAtIndex:0]; NSString* file= [documentDirectory stringByAppendingPathComponent:@"image.png"]; [data writeToURL:[NSURL URLWithString:file] atomically:YES]; NSURL url...

NSURL/NSURLRequest is unexpectedly nil

ios,swift,uiwebview,nsurl,nsurlrequest

The problem is that you do not know what is nil. Add more logging, like this: let url = NSURL(string: "http://www.urartuuniversity.com/content_images/pdf-sample.pdf")! let request = NSURLRequest(URL: url) println(url) println(request) println(webView) webView.loadRequest(request) In this way, by putting your app through its paces and trying to reproduce the crash, you will discover, just...

While giving a space i am getting 'unexpectedly found nil while unwrapping an Optional value'

ios,web-services,swift,nsurl

You have to use .stringByAddingPercentEscapesUsingEncoding "http://www.domain.com/?z=your string".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! // "http://www.domain.com/?z=your%20string" ...

Objective-C NSURL With Non-Alphabetical Characters

ios,objective-c,xcode,nsurl,non-ascii-chars

Problem Description From the documentation of [NSURL initWithString] Initializes an NSURL object with a provided URL string. - (id)initWithString:(NSString *)URLString Parameters - URLString The URL string with which to initialize the NSURL object. This URL string must conform to URL format as described in RFC 2396, and must not be...

Cannot parse NSString to NSURL with two # or more

ios,objective-c,nsstring,nsurl

If you can require iOS 7.0 or later, then I recommend that you use NSURLComponents: NSURLComponents* components = [[NSURLComponents alloc] init]; components.scheme = @"tel"; components.host = @"18005333333,,,1#,,,421#,,,959538788"; NSURL* telURL = components.URL; [myApp openURL:telURL]; Otherwise, you may need to use CFURLCreateStringByAddingPercentEscapes() to forcibly percent-escape the "#" characters. It's not really correct...

Not downloading files to NSDocumentsDirectory correctly?

ios,swift,download,nsurlconnection,nsurl

import UIKit let documentsDirectoryUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL var error:NSError? var response:NSURLResponse? let data = NSURLConnection.sendSynchronousRequest(NSURLRequest(URL: NSURL(string: "http://i.stack.imgur.com/Xs4RX.jpg")!), returningResponse: &response, error: &error) if let data = data where error == nil { let destinationUrl = documentsDirectoryUrl.URLByAppendingPathComponent(response!.suggestedFilename!)...

Playing a sound from local Documents

ios,nsurl,nsdocumentdirectory

Change NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:strPointSound ofType:@"mp3"]]; to NSURL *soundURL = [NSURL fileURLWithPath:strPointSound]; Because the Document folder is not a part of your bundle, so you do not need it....

XSS vulnerability when sending an URL to Safari iOS

ios,xcode,security,xss,nsurl

URL context based XSS can be appear when app try to reflect output inside href attribute. <a href="DATA_REFLECTS_HERE">DATA_REFLECTS_HERE</a> AS you can see same variable can be use 2 diffirent context. First one is inside of href, second one is directly HTML context. Most command XSS payloads(javascript:alert(1) etc) and mitigation can...

Large number not correct from UITextField

iphone,nsurl

The best you can do is pass the phone number as a NSString. Why convert it to a number? it can even contain a + sign. You can trim all unwanted characters by doing: NSCharacterSet *charactersToRemove = [[NSCharacterSet characterSetWithCharactersInString:@"+0123456789"] invertedSet]; NSString *newPhoneNumber = [[self.phoneTextField.text componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""]; newPhoneNumber = [NSString stringWithFormat:@"tel:%@",...

How to determine file equivalency between app sessions prior to OS X 10.10?

objective-c,osx,cocoa,nsurl,nsfilemanager

The solution I eventually settled upon was to assign each file my app touched a UUID that was stored in the file's extended attributes under a key unique to my app. Extended attributes follow a file when it is moved or copied. When reading in a directory structure, I check...

Remove port from NSURL

objective-c,cocoa,nsurl

You can write code to perform normalisation. NSURL may do some for you, but I don't think it's documented to do so. Removing the port number won't necessarily work towards normalisation, but you can do it. In both cases NSURLComponents will help you to by deconstructing the URL and allowing...

NSURL end with %20

objective-c,nsurl

%20 is nothing but white space. Because of stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding you see space as %20. If you have whitespace at the end, use below code to remove it. NSString *string = @" this text has spaces before and after "; NSString *trimmedString = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; ...

How to convert NSData with textEncoding utf-8 into NSURL

ios,objective-c,encoding,nsdata,nsurl

You're trying to load data that represents a PDF into an NSString. A PDF file does not consist of UTF-8 encoded characters that represent text, it's a file that contains header information, fonts, vector graphics AND text. The only solution to your problem in my mind is change the source...

Swift - session.dataTaskWithURL completionHandler never called

swift,nsurl,nsurlsession

The task never completes because it never gets started. You have to manually start the data task using its resume() method. let urlPath:String = apiURL + apiVersion + url + "?api_key=" + apiKey let url = NSURL(string: urlPath) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!, completionHandler: {(data, reponse, error)...

How can I get failed URL from didFailProvisionalNavigation method

ios,iphone,nsurl,wkwebview

You can use NSURLErrorFailingURLStringErrorKey to replace NSErrorFailingURLStringKey. If you jump to its definition in Xcode, you will find the below discussion. This constant supersedes NSErrorFailingURLStringKey, which was deprecated in Mac OS X 10.6. Both constants refer to the same value for backward-compatibility, but this symbol name has a better prefix....

NSURL Error code extraction

ios,xcode,error-handling,nsurl

You can't use: NSLog(@"%@", [error code]); Because code is NSInteger. Use: NSLog(@"%d", [error code]); Refer: NSError Class Reference for more details...

Encode URL contains special characters

ios,objective-c,special-characters,encode,nsurl

AS you said, http://some.com//en/it/name-50%-other-set-50%-/68 is a bad URL. What is the good URL you're supposed to have ? And why is there // after .com?...

iOS: Download .TXT file give strange result

ios,swift,nsurlconnection,nsurl

I found an interesting answer my download_file.txt has only character 'x' about 5 million characters to become 5MB iOS has 'some' algorithm that check the download file has the same character or text (it's also not the cache) and it no need to download the whole 5MB, instead it use...

AVAudioPlayer didn't run from url file in Swift Programming

swift,avaudioplayer,nsurl

You can not use NSURL(fileURLWithPath:) method to create a url from a web link. When creating url from links you need to use NSURL(string:) but you should download your data asynchronously using dataTaskWithUrl as follow: import UIKit import AVFoundation class ViewController: UIViewController { var player:AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad()...

NSUrl using stringwithformat to pass data to php page always returns sent value as zero [duplicate]

php,objective-c,nsurl,stringwithformat

I think you mean: $cid = $_GET["CategoryID"]; ^^^ Your code is wiiiide open to sql injection attacks as well. You should be using PDO for your queries: http://php.net/manual/en/book.pdo.php...

Can I create an NSURL that refers to in-memory NSData?

ios,cocoa,nsdata,nsurl

NSURL supports the data:// URL-Scheme (RFC 2397). This scheme allows you to build URLs in the form of data://data:MIME-Type;base64,<data> A working Cocoa example would be: NSImage* img = [NSImage imageNamed:@"img"]; NSData* imgData = [img TIFFRepresentation]; NSString* dataFormatString = @"data:image/png;base64,%@"; NSString* dataString = [NSString stringWithFormat:dataFormatString, [imgData base64EncodedStringWithOptions:0]]; NSURL* dataURL = [NSURL...

Using NSNumber numberWithBool in Swift

swift,ios8,nsurl,nsnumber

Some Swift types (Int, Bool, String, ...) are automatically bridged to the corresponding Objective-C type, so you can simply write: let success = fileToExclude.setResourceValue(true, forKey: NSURLIsExcludedFromBackupKey, error: &error) (More details in Working with Cocoa Data Types.)...

Swift URL Reponse is nil

session,swift,return,nsurl,nil

The dataTaskWithURL runs asynchronously. That means that the completionHandler closure will not be called by the time you return from fetchData. Thus, result will not have been set yet. As a result, you should not try to retrieve data synchronously from an asynchronous method. Instead, you should employ an asynchronous...

No known class method for selector 'URLAssetWithURL'

ios,objective-c,avfoundation,nsurl,avurlasset

As per the class reference at https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVURLAsset_Class/index.html the class method takes two parameters, the URL and some options. Change to: AVAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:audioFiles[indexPath.row]] options:nil]; waveformView.asset = asset; I would expect XCode's autocompletion and highlighting make it obvious that you were using a method that didn't exist......

How to call HTML file with css, js and images?

javascript,html,ios,zip,nsurl

This is an approach for you. From the context that you said that you have source files js and css. Here issue may be because of on run time these files are not loaded or compiler not able to find their location. For exmaple: <!--For CSS file html tag is-->...

redirect uri causing issues when navigating to an oauth url

swift,oauth-2.0,nsurl

I had a similar OAuth problem and didn't want to mess around with a web server so instead what I did was kinda cheeky. Make a UIWebView and put the request on the web view. Then delegate it to yourself and pass the redirect URL to be http://localhost:8000 (it can...

NSURL encoding with special charecters

ios,encoding,nsurl

Refer to NSString stringByAddingPercentEscapesUsingEncoding: you should use CFURLCreateStringByAddingPercentEscapes to custom which character you want to escape. - (NSString *) urlencodeStr:(NSString *)str { return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( NULL, (__bridge CFStringRef) str, NULL, CFSTR("!*'();:@+$,/?%#[]"), kCFStringEncodingUTF8)); } CFSTR("!*'();:@+$,/?%#[]") contains the characters will be escaped....

Converting URL to String and back again

swift,nsurl

fileURLWithPath() is used to convert a plain file path (e.g. "/path/to/file") to an URL. Your urlString is a full URL string including the scheme, so you should use let url = NSURL(string: urlstring) to convert it back to NSURL. Example: let urlstring = "file:///Users/Me/Desktop/Doc.txt" let url = NSURL(string: urlstring) println("the...

Inheritance, AFNetworking, Good Practices?

ios,inheritance,nsurl,afnetworking-2,nsurlsession

AFNetworking is a very good library for networking. If you need something more advanced than basic stuff and you don't want to reimplement them by yourself, it is a good (best?) choice. Note that AF 2.0 is not compatible with older versions of OSX and iOS, so pay attention to...

Swift: 'ViewController.Type' does not have a member named 'URL'

ios,swift,nsurlconnection,nsurl

None of your code is in a method, wrap it up in a method and call the method when appropriate.

Unsupported URL on ios 8

ios8,nsurl,nsurlrequest

This is how I got it resolved. Good Luck! NSString *google = @"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=500&types=%@&key=%@"; NSString *link = [NSString stringWithFormat:google, coordinate.latitude, coordinate.longitude, types, GOOGLE_KEY]; NSURL *url = [NSURL URLWithString:[link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url]; ...

Open link in UITextView within App

ios,swift,uitextview,nsurl,uitextviewdelegate

The shouldInteractWithURL function should return true only if the link has to be opened up in Safari. If you are handling the link yourself you should return false. Check the changed line in the code below. You can also use optional chaining instead of the if condition to call pushViewController...

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

ios,url,nsurl,ios9

You can add exceptions for specific domains in your Info.plist: <key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>testdomain.com</key> <dict> <key>NSIncludesSubdomains</key> <false/> <key>NSExceptionAllowInsecureHTTPSLoads</key> <false/> <key>NSExceptionRequiresForwardSecrecy</key> <true/> <key>NSExceptionMinimumTLSVersion</key> <string>TLSv1.2</string>...

URL Variable is not being recognized using NSURL

ios,swift,parsing,web-scraping,nsurl

You just need to move those lines inside viewDidLoad or create a method with them: override func viewDidLoad() { super.viewDidLoad() let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in println(NSString(data: data, encoding: NSUTF8StringEncoding)) } task.resume() } ...

How do I get the data from an NSURLSession as a string?

ios,swift,nsurl,nsurlsession

If your problem is that it is empty outside of the task, that is because it is going out of scope after the completion block ends. You need to save it somewhere that has a wider scope. let url = NSURL(string: apiCall) var dataString:String = "" let task = NSURLSession.sharedSession().dataTaskWithURL(url!)...

display images from iOS gallery

ios,image,uiimage,nsurl,xamarin.forms

I solved by using a stream: var s = originalImage.AsPNG ().AsStream (); SharedView.SetImageStream(s); In the PCL side: public void SetImageStream(System.IO.Stream s) { theImageView.Source = ImageSource.FromStream(() => s); } ...

Strange Invisible Character in String causing NSURL to fail

ios,string,swift,nsurl,addressbook

You have to use .stringByAddingPercentEscapesUsingEncoding to convert special characters. let myLink = "http://google.com" let myUrl = NSURL(string: myLink.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)! ...

Get position of NSString in string - iOS

ios,objective-c,string,nsstring,nsurl

You can use: NSRange range = [urlString rangeOfString:@"://"]; range.location will give you the first index from where the "://" starts and you can use it as: NSString *newAddress = [urlString substringFromIndex:range.location]; and append your prefix: NSString *finalAddress = [NSString stringWithFormat:@"%@%@", prefixString, newAddress]; ...

(OS X) Determine if file is being written to?

objective-c,osx,cocoa,nsurl,nsfilemanager

There aren't great ways to do this. If you can be certain that the writer is using NSFileCoordinator, then you can also use that to coordinate your access to the file. Likewise, if you're sure that the writer has opted in to advisory locking, you could try to open the...

Encode NSURL when query params contain ampersand

ios,objective-c,utf-8,nsurl

I found the solution, and it was with NSURLComponents - at this point a completely undocumented class added in iOS7. NSURLComponents *components = [NSURLComponents new]; components.scheme = @"http"; components.host = @"myurl.com"; components.path = [NSString stringWithFormat:@"%@/mypath/%@", @"/mobile_dev/api", user_id]; components.percentEncodedQuery = [NSString stringWithFormat:@"name=%@", [term urlEncodeUsingEncoding:NSUTF8StringEncoding]]; NSURL *fullURL = [components URL]; By using...

Losing NSURL property after viewDidLoad

ios,objective-c,uiwebview,nsurl

Calling performSegueWithIdentifier will actually instantiate a new instance of BrowserViewController. I'm not familiar enough with storyboards to know how to do this, but there is a UIViewController callback that will let you know when a segue is being performed, so that you can pass it the incomingURL. If you want...

How do I get the NSURLResponse before the downloadTaskWithURL finishes?

ios,swift,nsurl,nsurlsession

Do not use Shared session Keep a session property,use this function to init. init(configuration configuration: NSURLSessionConfiguration?, delegate delegate: NSURLSessionDelegate?, delegateQueue queue: NSOperationQueue?) -> NSURLSession Then use dataTask to download image In this delegate method you can get Response optional func URLSession(_ session: NSURLSession, dataTask dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler...

Convert String to NSURL is return nil in swift

string,swift,nsurl

As suggested by the Martin R, I see THIS post and I converted that objective-c code to swift and I got this code: var url : NSString = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitud‌​e),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US" var urlStr : NSString = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! var searchURL : NSURL = NSURL(string: urlStr)! println(searchURL) and this is working correctly....

UIApplication sharedapplication openURL not working

ios,objective-c,nsurl,uiapplication,openurl

Try it without the encoding like this. - (IBAction)facebookButtonPress:(id)sender { NSLog(@"fb hit"); [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[@"www.facebook.com/asbreckenridge" ]]]; } Also try changing the URL to http://www.facebook.com/asbreckenridge...

I am not able to get data from my localhost using this code. Please help me. I am getting nil

ios,swift,nsurl

You should pass in full URL var data = NSData(contentsOfURL: NSURL(string: "http://192.168.1.8:8888/service.php")!) println(data) ...

%2C in NSURLComponents turns to %2525252C - swift

ios,api,swift,nsurl

Just do let bbox = "\(lat1),\(lat2),\(lon1),\(lon2)", so then when it gets turned into a URL, the comma converts to %2C. I removed the + because you don't need it at all, you can just string them together in one string.

NSURL path getting CGPathRef instead of NSString

ios,objective-c,nsstring,nsurl

From The NSString reference, you can use : NSString* theFileName = [[string lastPathComponent] stringByDeletingPathExtension] The lastPathComponent call will return "thefile.ext", and the stringByDeletingPathExtension will remove the .ext from the end. src: Objective-C: Extract filename from path string...

Retrieve nested objects from JSON - Objective C

objective-c,json,nsdata,nsurl

You are parsing your JSON data in wrong way, you are parsing JSON directly to Array but as per your JSON format your JSON will return an NSDictionary not NSArray. -(void)retrieveLocalWeatherService { NSURL *url = [NSURL URLWithString:getLocalWeather]; NSData *data = [NSData dataWithContentsOfURL:url]; NSDictionary *weatherJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; NSArray...

Swift - UILabel from URL

ios,swift,uilabel,nsurl

If you don't want to use sessions, you can also use the simpler NSURLConnection Class, something like this: let url = NSURL(string: "https://wordpress.org/plugins/about/readme.txt") let request = NSURLRequest(URL: url!) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in println(NSString(data: data, encoding: NSUTF8StringEncoding)) dispatch_async(dispatch_get_main_queue()) { // Do stuff on the UI thread self.textField.text =...

Add a custom tag to an url in xcode

ios,xcode,nsurl,custom-tag

You can either using NSDictionary or NSObject to store your URL instance and the associated tag value. I would prefer using NSObject: Create a subclass of NSObject called MyNSURLObject. For MyNSURLObject.h: (you don't need to modify MyNSURLObject.m file) #import <Foundation/Foundation.h> @interface MyNSURLObject : NSObject @property(strong, nonatomic) NSURL *myURL; @property(strong, nonatomic)...

Parsing JSON into a usable format

swift,nsarray,nsdictionary,nsurl

The trick is to declare the right type for the cast. For your data we are using [String: [[String: AnyObject]]]: a dictionary with a String as key and an array of dictionaries as value, these dictionaries have their value as AnyObject because there's several possible types. After a successful decoding,...

Checking if an NSURL is instantiated in Swift vs. Objective-C

objective-c,swift,core-data,nsurl

You can check if it's equal to nil, or you can use the if let to unwrap it if it exists. fileManager.URLForUbiquityContainerIdentifier(nil) returns an optional NSURL, so you handle that as such: let iCloud = fileManager.URLForUbiquityContainerIdentifier(nil) // Remove the "!", and this should return an optional if iCloud != nil...

NSUrl from NSString returns null

ios,objective-c,parsing,nsstring,nsurl

From the apple documentation "An NSURL object initialized with URLString. If the URL string was malformed or nil, returns nil." Your stringURL isn't a correct formed url. For reference: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/clm/NSURL/URLWithString: What you actually want to use is: fileURLWithPath: isDirectory: instead. NSURL *url = [NSURL fileURLWithString:[stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]...

How to decode NSURL in iOS?

ios,objective-c,nsurl,decoding

you are doing it in wrong way. this is the right way NSString *urlString = @"http://www.janvajevu.com/webservice/categorylist.php?category=%E0%AA%B8%E0%AB%8D%E0%AA%B5%E0%AA%BE%E0%AA%B8%E0%AB%8D%E0%AA%A5%E0%AA%AF&page="; NSURL *targetURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%d",urlString,pageNumber]]; NSLog(@"targetURL is : %@",targetURL); ...

Determine if a Volume is a Disk Image (DMG) from code

objective-c,osx,filesystems,nsurl,diskimage

You can obtain this information using the DiskArbitration framework. To use the example below, you must link against and #import it. #import <DiskArbitration/DiskArbitration.h> ... - (BOOL)isDMGVolumeAtURL:(NSURL *)url { BOOL isDMG = NO; if (url.isFileURL) { DASessionRef session = DASessionCreate(kCFAllocatorDefault); if (session != nil) { DADiskRef disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, (__bridge...

This NSURL request compiles, but doesn't work as expected. What am I missing?

ios,objective-c,xcode,boolean,nsurl

It's not pretty, but I got it to work. I took out the BOOL and googleSearch functions and dumped everything in textFieldShouldReturn. Rather than have a bunch of code dumped into textFieldShouldReturn, I'd like to break this up into more re-usable code (that works). While it works, I think it's...

How to access file using pathForResource:ofType:inDirectory

ios,objective-c,avfoundation,nsurl

If Supporting Files folder is the Supporting Files group you see in every Xcode project by default than the inFolder: argument is not needed as Supporting Files is a Xcode grouping and not a real folder. So you should do: NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"smoothjazz" ofType:@"mp3"]; This should work....

Resolution of NSURL bookmark fails for an external drive in Yosemite

cocoa,usb,nsurl,security-scoped-bookmarks

This bug seems to be resolved in Mac OS X El Capitan.

How to show the image via http url in AlertView in Objective-C?

ios,objective-c,uiimage,uialertview,nsurl

You cant add image in AlertView. It was possible prior to iOS 7. You can create a custom AlertView and add image to it. Also check out this https://github.com/wimagguc/ios-custom-alertview...

NSURL breaking port string with colon

ios,escaping,nsurl

Actually the solution is pretty simple... just add the scheme. Something like this: NSURL *baseURL = [NSURL URLWithString:@"http://193.178.0.99:9000"]; NSString *absoluteString = [[NSURL URLWithString:@"api/whatever" relativeToURL:baseURL] absoluteString]; // Prints => http://193.178.0.99:9000/api/whatever ...

How to pass an array in an url query parameter using nsurl in objective-c?

ios,objective-c,nsurl

Create a collection and then use NSJSONSerialization to create JSON data representation. Use the resulting data as the POST data. NSDictionary *parameters = @{ @"title": @"Design Milk", @"id": @"feed/http://feeds.feedburner.com/design-milk", @"categories": @[ @{ @"id": @"user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/design", @"label": @"design" }, @{ @"id": @"user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/weekly", @"label": @"weekly" }, @{ @"id": @"user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/global.must", @"label": @"must...

iOS8, Swift: fileURLWithPath - missing argument for parameter error

ios,swift,nsurl

The problem is that you're trying to chain methods when there are optionals in the chain. NSURL.fileURLWithPath(applicationDocumentsDirectory) returns NSURL? type. When you try to execute method URLByAppendingPathComponent on it, it throws a compiler error. I know it's kind of sucks that the compiler error is totally unrelated to the real...

NSData is returning nil for same file at different filepaths

ios,objective-c,ios-simulator,nsdata,nsurl

You are trying to read a file outside of the running app's sandbox. While both may exist, presumably you are running the application with ID "FD17AD64-EAF9-4578-B50D-0B5BF6F2DEFF", which is why that URL is working while the other one isn't. I would recommend watching the WWDC video A Practical Guide to the...

Issue returning NSURL in Swift

swift,oauth,nsurl

Replace this: private func formAuthURL ((Void) -> NSURL) With this: private func formAuthURL() -> NSURL Here is the basic form of function declarations in swift: func functionName(paramName:ParamType) -> ReturnType Based on this you can see that your function was trying to take a closure with the form (Void) -> NSURL...

writeToFile: returning correct path, but no file?

nsdata,nsurl,writetofile,cgimageref,nsbitmapimagerep

Needed to be: [data writeToURL:[documentsURL URLByAppendingPathComponent:@"Copyfeed-Image.png"] atomically:YES]; Because I was trying to write to a path, but was returning a URL, you can only write to path it seems if you first create a file there....

POST request not receiving all json

ios,json,nsurlconnection,nsurl,nsurlconnectiondelegate

In this section: if(!receivedData){ receivedData = [[NSMutableData alloc]init]; [receivedData appendData:data]; } You are only appending data if the object hasn't been created yet. You want to append every time. That if statement should read like this: if(!receivedData){ receivedData = [[NSMutableData alloc]init]; } [receivedData appendData:data]; ...

NSURL won't init from string to remote font file (.TTF)

ios,file,swift,fonts,nsurl

I am trying to load fonts dynamically in my app, given a provided URL path to font files that are hosted on my server You can't. You can include a font in your app bundle, and you can download a font from Apple by calling CTFontDescriptorMatchFontDescriptorsWithProgressHandler. But you can't...

NSURL found nil while unwraping an Optional value

swift,nsurl,nsurlrequest

The | character its not a valid URL character so you must replace it with percent escape character. Encoding whole string will do that automatically for you var stringUrl = "https://roads.googleapis.com/v1/snapToRoads?path=-35.27801,149.12958|-35.28032,149.12907" let URL = NSURL(string: stringUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)! ...

How to make HTTP request to php server in Swift iOS

php,ios,swift,nsurl

add request.HTTPMethod = "POST" since you are trying to do a post request, aren't you? and btw: when i try to use your URL outside of xcode, the request works (status 200). the problem seems to be in your php script: Notice: Undefined index: userid in /home/techicom/public_html/varun/ios-api/userRegister.php on line 4...

Getting URL of UIImage selected from UIImagePickerController

ios,swift,ios8,uiimagepickercontroller,nsurl

Okay, I've solved the issue. All you have to do is simply grab the image (info[UIImagePickerControllerOriginalImage] as UIImage) and save to the given directory. If you need to save only 1 picture it works great. The code id below. func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { let imageURL...

How to use UIDocument in iOS for remote documents?

ios,uiwebview,nsurlconnection,nsurl,uidocumentinteraction

The answer here really lies in Chaithra's comment: UIDocumentInteractionController: invalid scheme http. Only the file scheme is supported To solve this problem you need to download the PDF file, obtain a local URL for it and can then pass it onto the UIDocumentInteractionController. Using AFNetworking as a baseline the following...

objective c - How to tell if an NSURL is formatted as a phone number

ios,nsurl,detect,phone

There IS a better way. An NSURL object has an attribute of scheme, which will identify what type of URL it is. if ([URL.scheme isEqualToString:@"tel"]) { // handle telephone case here } else { // handle http or other case here } The documentation says the scheme could be considered...

How do I add a number to an NSURL? Too many arguments error

ios,objective-c,nsurl

What is wrong is on NSURL *url = [NSURL URLWithString:@"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]]; you are calling URLWithString: and then pass in a string that is not being formatted correctly. If you want to do it all on one line then you need to be using stringWithFormat: like NSURL *url = [NSURL URLWithString:[NSString...

unable to display urls in table @ masterViewController

uitableview,swift,nsurl

You are written cell.textLabe!.text you have to write cell.textLabel!.text To print url string in textLabel cell.textLabel!.text = urls[indexPath.row].absoluteString! ...

Swift - Using less than “<” operator in REST api search with NSURLRequest

swift,nsurl,nsurlrequest

Try encoding that part of your URL. let urlString = https://"company/api/v2/search.json?query=type:ticket%20" let queryString = "status<solved".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) let fullUrl = urlString + queryString ...

Remove all text after a symbol - iOS

ios,objective-c,xcode,webview,nsurl

Try this I hope it may help you. NSString *str1 = @"http://www.bbc.co.uk/news/technology-30447248%23sa-ns_mchannel=rss&ns_source=PublicRSS20-sa%20%20%20%20%20%20%20%20"; NSRange range = [str1 rangeOfString:@"sa"]; NSString *newString = [str1 substringToIndex:range.location]; NSLog(@"%@",newString); ...

Swift - NSURL fileURLWithPath not unwrapped?

swift,nsurl,optional

Here's the issue : urlForScene returns a NSURL, whereas fileURLWithPath: returns an optional : NSURL?, (as per the doc). So, the issue is, fileURLWithPath: might return nil (this is why it returns a NSURL?), and you return a non-nil object (a NSURL). The compiler tells you to unwrap it, but...

How do I give inputs through NSURL [closed]

ios,swift,nsurl

The likely answer is "You can't." There is no secret sauce that lets you generate a URL that fills in fields in a web page. If the website you are using isn't designed to prepopulate the search field with a parameter from an URL then you won't be able to...

Swift NSURLSession App crashes on cellular data

ios,xcode,swift,nsurl,nsurlsession

What you're doing is web scraping which is inherently unstable, particularly the way you're doing it. There is no guarantee that the content returned from that url will match up with the precise text you're using to break up the html. You've already found that you get different responses depending...

impossible to build a dynamic NSURL to put images in UIImage

ios,swift,uiimageview,uiimage,nsurl

Do what the error tells you to do. Instead of: var imageURL = NSURL.URLWithSting(picture) do: var imageURL = NSURL(string: picture)...

Swift parsing attribute name for given elementName

swift,xml-parsing,nsxmlparser,nsurl,xml-attribute

Building a dictionary of [city:id] can be a solution for you. I have implemented a simple solution based on the article about lifecycle of NSXMLParser at http://www.codeproject.com/Articles/248883/Objective-C-Fundamentals-NSXMLParser . Following method is called when when an element is starting. You can retrieve city id attribute and save it in an instance...

NSURL returning nil for certain cases

objective-c,nsurl,nsurlsession

You said: I had to add "\" in front of the apostrophes as is evident from my code because PHP needs to have the " ' " escaped in its URLs. But by doing so, it seems like I've violated some requirement set out for NSURL. What do you guys...

Program skips NSURLRequest used to download txt file, if placed in IB action with other code

ios,objective-c,curl,nsurl

You must create a NSOperationQueue instance: [NSURLConnection sendAsynchronousRequest:request [NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { ...